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

时间:2014-05-11 14:22:24

标签: c# wpf xaml binding

我有两个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;
    }
}

3 个答案:

答案 0 :(得分:1)

删除&#34; ToggleButton&#34;来自路径属性。
您只需要属性名称。

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

答案 1 :(得分:0)

以下是我的工作,我将它们全部发送到同一个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;
                };

答案 2 :(得分:0)

找到解决方案:

我需要修改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);
    }
}