Search code examples
c#wpfmenuitemischecked

In WPF MenuItem, it it possible to use the opposite value of a bool


In WPF, I have two menu items that are mutually opposite (X ticked, then Y unticked and vice versa).

Is it possible to use single bool property to bind these two?

For example below, I have used !IsX and it is not working!

<MenuItem Header="X or Y">
    <MenuItem IsCheckable="True" Header="Is X?" IsChecked="{Binding Path=IsX, Mode=TwoWay}" />
    <MenuItem IsCheckable="True" Header="Is Y?" IsChecked="{Binding Path=!IsX, Mode=TwoWay}" />
</MenuItem>

Solution

  • You need to write a custom converter for that:

    [ValueConversion(typeof(bool), typeof(bool))]
    public class InverseBooleanConverter: IValueConverter
    {
        #region IValueConverter Members
    
        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");
    
            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");
    
            return !(bool)value;
        }
    
        #endregion
    }
    

    And then in your markup:

    <MenuItem Header="X or Y">
        <MenuItem IsCheckable="True" Header="Is X?" IsChecked="{Binding Path=IsX, Mode=TwoWay}" />
        <MenuItem IsCheckable="True" Header="Is Y?" IsChecked="{Binding Path=IsX, Mode=TwoWay, Converter={StaticResource InverseBooleanConverter}}" />
    </MenuItem>
    

    Also you should create an instance of that in your resource file