You can create an enum
that contains the values of the RadioButton
objects as names (roughly) and then bind the IsChecked
property to a property of the type of this enum
using an EnumToBoolConverter
.
public enum Options
{
All, Current, Range
}
Then in your view model or code behind:
private Options options = Options.All; // set your default value here
public Options Options
{
get { return options; }
set { options = value; NotifyPropertyChanged("Options"); }
}
Add the Converter
:
[ValueConversion(typeof(Enum), typeof(bool))]
public class EnumToBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || parameter == null) return false;
string enumValue = value.ToString();
string targetValue = parameter.ToString();
bool outputValue = enumValue.Equals(targetValue, StringComparison.InvariantCultureIgnoreCase);
return outputValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || parameter == null) return null;
bool useValue = (bool)value;
string targetValue = parameter.ToString();
if (useValue) return Enum.Parse(targetType, targetValue);
return null;
}
}
Then finally, add the bindings in the UI, setting the appropriate ConverterParameter
:
<RadioButton Content="All Pages" IsChecked="{Binding Options, Converter={
StaticResource EnumToBoolConverter}, ConverterParameter=All}" />
<RadioButton Content="Current Page" IsChecked="{Binding Options, Converter={
StaticResource EnumToBoolConverter}, ConverterParameter=Current}" />
<RadioButton Content="Page Range" IsChecked="{Binding Options, Converter={
StaticResource EnumToBoolConverter}, ConverterParameter=Range}" />
Now you can tell which is set by looking at the Options
variable in your view model or code behind. You'll also be able to set the checked RadioButton
by setting the Options
property.