繁体   English   中英

WPF ToggleButton绑定不起作用

[英]WPF ToggleButton Binding Not Working

我有两个ToggleButtons; 我试图通过将它们绑定到布尔值来使它们像一对单选按钮一样工作,但是它不起作用。 这是我到目前为止的内容:

<ToggleButton Name="YesButton" Margin="5,0" Width="100" IsChecked="{Binding YesBool, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">Yes!</ToggleButton>

<ToggleButton Name="NoButton" Margin="5,0" Width="100" IsChecked="{Binding NoBool, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">No!</ToggleButton>

public partial class MainWindow : Window
{
    public MainWindow()
    {
        DataContext = this;
        InitializeComponent();
    }
}

public class Thingy : INotifyPropertyChanged
{
    private bool _yesno;

    public bool YesBool
    {
        get { return _yesno; }
        set { _yesno = value; NotifyPropertyChanged("YesBool"); }
    }

    public bool NoBool
    {
        get { return !_yesno; }
        set { _yesno = !value; NotifyPropertyChanged("NoBool"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

据我所知,遇到此问题的其他所有人都拼写错误或未使用NotifyPropertyChanged,但是(据我所知)我正在做这两种事情。 我究竟做错了什么?

将您的xaml中的DataContext设置为Thingy类,而不是“ this”窗口。

您的问题是未指定布尔值是必需的还是仅用于帮助您获得所需的行为。

因此,如果您不需要它们,也可以使用某个功能,取消选中另一个按钮。 这也可以用于2个以上的ToggleButton。
如果可以确定除ToggleButtons之外没有其他同类,那么也可以不进行类型检查就进行foreach循环。

public void ToggleButtonChecked(object sender, RoutedEventArgs e)
    {
        ToggleButton btn = sender as ToggleButton;
        if (btn == null)
            return;
        Panel container = btn.Parent as Panel;
        if (container == null)
            return;

        for (int i = 0; i<container.Children.Count; i++)
        {
            if (container.Children[i].GetType() == typeof(ToggleButton))
            {
                ToggleButton item = (ToggleButton)container.Children[i];
                if (item != btn && item.IsChecked == true)
                    item.IsChecked = false;
            }
        }
    }

XAML

<ToggleButton x:Name="tb1" Checked="ToggleButtonChecked"/>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM