WPF Radiobutton (two) (binding to boolean value)

前端 未结 8 2019
深忆病人
深忆病人 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:25

    You can use a value-converter that reverts the boolean value:

    With that converter, bind one Checkbox.IsChecked-property to the boolean value without the converter and one CheckBox.IsChecked-property with the converter. This should do the trick.

    Here the code for such a converter. I have copied it from here and added some lines of code. There you will find more information about.

    public class BoolToOppositeBoolConverter : IValueConverter {
        public object Convert(object value, Type targetType, object parameter,System.Globalization.CultureInfo culture) {
            if (targetType != typeof(bool)) {
                throw new InvalidOperationException("The target must be a boolean");
            }
            if (null == value) {
                return null;
            }
                        return !(bool)value;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter,System.Globalization.CultureInfo culture) {
            if (targetType != typeof(bool)) {
                throw new InvalidOperationException("The target must be a boolean");
            }
            if (null == value) {
                return null;
            }
            return !(bool)value;
        }
    } 
    

    To use it, declare it in the resource-section.

     
    

    And the use it in the binding as a static resource:

    
    
    

    Please note, the converter is only a simple example. Implement it neatly if you want to use it in productive code. I have not tested it. Make a comment if its not working.

提交回复
热议问题