将ToggleButton IsChecked属性绑定到另一个ToggleButton不工作

本文关键字:ToggleButton 另一个 工作 绑定 IsChecked 属性 | 更新日期: 2023-09-27 18:02:50

我有两个ToggleButtons

我需要将一个IsChecked属性绑定到另一个ToggleButton

我使用自定义Converter来反转值。

然而,它不工作?下面是我的代码:

XAML:

<ToggleButton 
    IsChecked="{Binding Path=ToggleButton.IsChecked, ElementName=menuCatUit, 
    Converter={StaticResource InvertBool}}"/>
<ToggleButton x:Name="menuCatUit" IsChecked="True" />
代码:

[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;
    }
}

将ToggleButton IsChecked属性绑定到另一个ToggleButton不工作

将"ToggleButton"从path属性中移除
您只需要属性名。

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

我是这样做的,我把它们都发送到同一个Checked和UnChecked事件:

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;
        }
    }

然后检查哪个ToggleButton被选中了像这样做

switch (Toggle.Name)
                {
                    case ("Button1"): /*MyCode*/ break;
                };

找到解决方案:

我需要编辑我的converter,因为ToggleButton使用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);
    }
}