我有
<DataGridCheckBoxColumn
Binding="{Binding Path=Foo, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
/>
和
public bool Foo{ get; set; }
Checking/Unchecking sets Foo
,但Foo
代码中的设置不会更改 Checkbox 状态。有什么建议吗?
当您将PropertyChanged
Foo 设置为DataContext
. 通常,它看起来像:
public class ViewModel : INotifyPropertyChanged
{
private bool _foo;
public bool Foo
{
get { return _foo; }
set
{
_foo = value;
OnPropertyChanged("Foo");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
var propertyChanged = PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
如果您调用Foo = someNewvalue
,该PropertyChanged
事件将被引发并且您的 UI 应该被更新
我花了几个小时寻找这个问题的完整答案。我猜有些人认为搜索这个问题的其他人知道基础知识——有时我们不知道。通常缺少有关设置表单数据上下文的一个非常重要的部分:
public YourFormConstructor()
{
InitializeComponent();
DataContext = this; // <-- critical!!
}
我的复选框控件是在 xaml 文件中设置的,如下所示:
<CheckBox x:Name="chkSelectAll" IsChecked="{Binding chkSelectAllProp, Mode=TwoWay}" HorizontalAlignment="Left"/>
"Path=" 和 "UpdateSourceTrigger=..." 部分似乎是可选的,所以我将它们排除在外。
我在 ListView 标题列中使用此复选框。当有人选中或取消选中复选框时,我希望 ListView 中的所有项目也被选中或取消选中(选择/取消选择所有功能)。我在示例中保留了该代码(作为“可选逻辑”),但您的复选框值逻辑(如果有)将替换它。
The ListView contents are set by browsing for a file, and when a new file is selected, code sets the ListView ItemsSource and the CheckBox is checked (selecting all the new ListView items), which is why this two-way operation is required. 此示例中不存在该部分代码。
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));
}