我花了几个小时寻找这个问题的完整答案。我猜有些人认为搜索这个问题的其他人知道基础知识——有时我们不知道。关于设置表单数据上下文的一个非常重要的部分通常会丢失:
public YourFormConstructor()
{
InitializeComponent();
DataContext = this; // <-- critical!!
}
我的复选框控件在 xaml 文件中设置如下:
<CheckBox x:Name="chkSelectAll" IsChecked="{Binding chkSelectAllProp, Mode=TwoWay}" HorizontalAlignment="Left"/>
“Path=" 和 "UpdateSourceTrigger=..." 部分似乎是可选的,所以我将它们省略了。
我在 ListView 标题列中使用此复选框。当有人选中或取消选中复选框时,我希望 ListView 中的所有项目也被选中或取消选中(选择/取消选择所有功能)。我在示例中保留了该代码(作为“可选逻辑”),但您的复选框值逻辑(如果有)将替换它。
ListView的内容是通过浏览文件来设置的,当一个新的文件被选中时,代码设置ListView ItemsSource并且CheckBox被选中(选中所有新的ListView项),这就是为什么这种双向操作的原因必需的。此示例中没有该部分代码。
xaml.cs 文件中处理 CheckBox 的代码如下所示:
// backing value
private bool chkSelectAllVal;
// property interchange
public bool chkSelectAllProp
{
get { return chkSelectAllVal; }
set
{
// if not changed, return
if (value == chkSelectAllVal)
{
return;
}
// optional logic
if (value)
{
listViewLocations.SelectAll();
}
else
{
listViewLocations.UnselectAll();
}
// end optional logic
// set backing value
chkSelectAllVal = value;
// notify control of change
OnPropertyChanged("chkSelectAllProp");
}
}
// object to handle raising event
public event PropertyChangedEventHandler PropertyChanged;
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}