I have a groupbox with some radiobuttons. How do I get to know which one which is checked? I am using WPF and following MVVM.
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
:
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.