Question

I have two ToggleButtons.

I need to bind one IsChecked property to the other ToggleButton.

I use a custom Converter to inverse the value.

However, it's not working? Here's my code:

XAML:

<ToggleButton 
    IsChecked="{Binding Path=ToggleButton.IsChecked, ElementName=menuCatUit, 
    Converter={StaticResource InvertBool}}"/>

<ToggleButton x:Name="menuCatUit" IsChecked="True" />

Code:

[ValueConversion(typeof(bool), typeof(bool))]
public class InverseBooleanConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (targetType != typeof(bool))
            throw new InvalidOperationException("The target must be a boolean");

        return !(bool)value;
    }
}
Was it helpful?

Solution 3

Found the solution:

I needed to edit my converter because ToggleButton uses a nullable bool.

[ValueConversion(typeof(bool?), typeof(bool))]
public class InverseNullableBool : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (targetType != typeof(bool?))
            throw new InvalidOperationException("The target must be a nullable boolean");

        bool? b = (bool?)value;
        return !(b.HasValue && b.Value);
    }
}

OTHER TIPS

Remove the "ToggleButton" from the path property.
You only need the property name.

<ToggleButton 
    IsChecked="{Binding Path=IsChecked, ElementName=menuCatUit, 
    Converter={StaticResource InvertBool}}"/>

Here is what i Do, I send them all to the same Checked and UnChecked event:

privateToggleButton Toggle;
public void ToggleButtonChecked(object sender, RoutedEventArgs e)
    {
        if (Toggle != null && Toggle != sender as ToggleButton)
        {
            Toggle.IsChecked = false;
        }

        Toggle = sender as ToggleButton;
    }

    public void ToggleButtonUnChecked(object sender, RoutedEventArgs e)
    {
        if (Toggle != null)
        {
            Toggle = null;
        }
    }

And then to check which ToggleButton is checked do something like this

switch (Toggle.Name)
                {
                    case ("Button1"): /*MyCode*/ break;
                };
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top