Determining checked Radiobutton from groupbox in WPF following MVVM

后端 未结 5 1776
有刺的猬
有刺的猬 2021-02-05 13:44

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.



        
5条回答
  •  太阳男子
    2021-02-05 13:50

    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.

提交回复
热议问题