WPF Radiobutton (two) (binding to boolean value)

前端 未结 8 2038
深忆病人
深忆病人 2020-12-24 10:51

I have a property of type boolean presented with checkbox.

I want to change that to two radiobuttons that bind on the same property presenting the value true/false.<

8条回答
  •  长情又很酷
    2020-12-24 11:42

    Little upgrade of RandomEngy's answer if you want your bool nullable (for no default value/Checked Radiobutton)

    public class BoolRadioConverter : IValueConverter
    {
        public bool Inverse { get; set; }
    
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            bool? boolValue = (bool?)value;
    
            return this.Inverse ? !boolValue : boolValue;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            bool? boolValue = (bool?)value;
    
            if (boolValue != null && (bool)!boolValue)
            {
                // We only care when the user clicks a radio button to select it.
                return null;
            }
    
            return !this.Inverse;
        }
    }
    

    and the rest is the same as his answer.

提交回复
热议问题