![](/img/trans.png)
[英]Binding Ischecked of a checkbox in wpf listbox on selectionchanged of the combobox
[英]ComboBox in ListBox doesn't update IsChecked properly
我使用以下方法制作了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仍處於未選中狀態……有人可以幫助我找出原因嗎?
您需要通過在CheckedListItem
實現INotifyPropertyChanged
接口來通知控件其綁定的屬性已更新:
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"));
}
}
}
您需要在CheckedListItem類上實現INotifyPropertyChanged接口,然后在屬性更改時發出通知。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.