WPF element databinding for IsEnabled (but for false)

15,034

Solution 1

You need to use what's called a value converter (a class that implements IValueConverter.) A very basic example of such a class is shown below. (Watch for clipping...)

public class NegateConverter : IValueConverter
{

    public object Convert( object value, Type targetType, object parameter, CultureInfo culture )
    {
        if ( value is bool ) {
            return !(bool)value;
        }
        return value;
    }

    public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture )
    {
        if ( value is bool ) {
            return !(bool)value;
        }
        return value;
    }

}

Then to include it in your XAML you would do something like:

<UserControl xmlns:local="clr-namespace:MyNamespace">
    <UserControl.Resources>
        <local:NegateConverter x:Key="negate" />
    </UserControl.Resources>

    ...
    <CheckBox IsEnabled="{Binding IsChecked, ElementName=rbBoth, Converter={StaticResource negate}}"
              Content="Show all" />

</UserControl>

Solution 2

<CheckBox>
                    <CheckBox.Style>
                        <Style TargetType="CheckBox">
                            <Setter Property="Visibility" Value="Visible" />
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding IsShowName }" Value="true">
                                    <Setter Property="Visibility" Value="Collapsed" />
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </CheckBox.Style>
  </CheckBox>

Solution 3

Your current syntax already serves your need. It will disable the checkbox if the radiobutton is not checked.

If you really want to invert the scenario, all you need is a Converter. Take a look at this sample.

Share:
15,034
SiN
Author by

SiN

xna, asp.net, .net, c#, sql-server, html, css, javascript

Updated on June 08, 2022

Comments

  • SiN
    SiN almost 2 years

    I'm a starter in WPF, and there's something I can't seem to figure out.

    I have a CheckBox that I would like to disable when a RadioButton is not selected. My current syntax is:

    <CheckBox IsEnabled="{Binding ElementName=rbBoth, Path=IsChecked}">Show all</CheckBox>
    

    So basically, I want IsEnabled to take the opposite value than the binding expression I'm currently supplying.

    How can I do this? Thanks.