1

我有简化的例子:

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]; - 没有改变。

在实际示例中,我在列表框的项目模板中有相同的复选框。所以行为是一样的——复选框的选择不会改变。

4

2 回答 2

3

您需要在 MyObject 类型上实现 INotifyPropertyChanged

于 2012-04-28T06:29:38.823 回答
2

请尝试以下代码:

public class MyObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

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

    private bool _isSelected;

    public bool IsSelected
    {
        get { return _isSelected; }
        set
        {
            _isSelected = value;
            NotifyPropertyChanged("IsSelected");
        }
    }

    public MyObject(bool isSelected)
    {
        this.IsSelected = isSelected;
    }
}
于 2012-04-28T07:23:21.973 回答