ListBox中的ComboBox不能正确更新IsChecked

时间:2011-03-25 02:01:21

标签: c# wpf data-binding combobox

我使用以下方法制作了一个CheckedListBox:

<ListBox x:Name="lst_checkBoxList" ItemsSource="{Binding}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding Name}" IsChecked="{Binding IsChecked}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

并使用以下内容填充它:

public List<CheckedListItem> listItems = new List<CheckedListItem>();

public class CheckedListItem
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsChecked { get; set; }

    public CheckedListItem(int id, string name, bool ischecked)
    {
        Id = id;
        Name = name;
        IsChecked = ischecked;
    }
}

private void button1_Click(object sender, RoutedEventArgs e)
{
    listItems.Add(new CheckedListItem(0, "item 1", false));
    listItems.Add(new CheckedListItem(0, "item 2", false));
    listItems.Add(new CheckedListItem(0, "item 3", false));
    listItems.Add(new CheckedListItem(0, "item 4", false));
    lst_checkBoxList.ItemsSource = listItems;
    listItems[0].IsChecked = true; //This correctly sets the first CheckBox as checked.
}

private void button2_Click(object sender, RoutedEventArgs e)
{
    listItems[0].IsChecked = true; //This does not affect the CheckBox, despite changing the value it is bound to.
}

如果在设置ItemsSource后立即更改其中一个CheckBox后面的数据,则会相应地勾选CheckBox,但是如果我尝试在代码中的任何其他位置更改值,则CheckBox仍然未选中...任何人都可以帮我工作为什么?

2 个答案:

答案 0 :(得分:1)

您需要通过在INotifyPropertyChanged中实施CheckedListItem界面来通知控件已绑定的属性已更新:

public class CheckedListItem : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private bool _IsChecked;
    public bool IsChecked 
    { 
        get { return _IsChecked; }
        set 
        {
            _IsChecked = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("IsChecked"));
        }
    }
}

答案 1 :(得分:0)

您需要在CheckedListItem类上实现INotifyPropertyChanged接口,然后通知任何属性更改。