我有简化的例子:
XAML:
<CheckBox IsChecked="{Binding Path=IsSelected, Mode=TwoWay}" Name="cb" />
<Button Name="button1" Click="button1_Click" />
后面的代码:
public partial class MainWindow : Window
{
private ObservableCollection<MyObject> collection = new ObservableCollection<MyObject>();
public MainWindow()
{
InitializeComponent();
collection.Add(new MyObject(true));
//grid.DataContext = collection[0];
}
private void button1_Click(object sender, RoutedEventArgs e)
{
collection[0].IsSelected = false;
}
}
public class MyObject
{
public bool IsSelected { get; set; }
public MyObject(bool isSelected)
{
this.IsSelected = isSelected;
}
}
尽管 collection[0].IsSelected 已更改,但 cb.IsChecked 不会通过单击按钮而更改。
即使我取消注释 grid.DataContext = collection[0]; - 没有改变。
在实际示例中,我在列表框的项目模板中有相同的复选框。所以行为是一样的——复选框的选择不会改变。