我有 3 个复选框。让我们称它们为 cb1
、cb2
和 cb3
。当检查cb1
和cb2
时,应该检查cb3
。我如何在 WPF 中实现它?我是 WPF 的新手。
提前致谢。
最佳答案
如果您使用的是 ViewModel,只需向其添加一个新的计算属性即可。
一个简单的 View 模型如下所示:
public class MyVieWModel : INotifyPropertyChanged
{
private bool _cb1Checked;
private bool _cb2Checked;
public bool CB1Checked
{
get { return _cb1Checked; }
set
{
_cb1Checked = value;
PropertyChanged(this, new PropertyChangedEventArgs("CB1Checked"));
PropertyChanged(this, new PropertyChangedEventArgs("CB3Checked"));
}
}
public bool CB2Checked
{
get { return _cb2Checked; }
set
{
_cb2Checked = value;
PropertyChanged(this, new PropertyChangedEventArgs("CB2Checked"));
PropertyChanged(this, new PropertyChangedEventArgs("CB3Checked"));
}
}
public bool CB3Checked
{
get { return _cb1Checked && _cb2Checked; }
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
设置CB1Checked
或CB2Checked
后,需要引发CB3Checked
也发生变化的事件。
您的 XAML 看起来像(这是来自内存...):
<CheckBox IsChecked={Binding CB1Checked}" />
<CheckBox IsChecked={Binding CB2Checked}" />
<CheckBox IsChecked={Binding CB3Checked, Mode=OneWay}" />
正如@wkl 在评论中指出的那样,第三个复选框应该是单向绑定(bind),因为无法设置该值。
一些 MVVM 框架可能会让你更容易一些,不过我没有使用过任何可以推荐的框架。
关于c# - 复选框绑定(bind) WPF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42416671/