[英]How to Checked and Unchecked Checked-box item of a List-box?
我是否正在使用列表框項目中的復選框,如何從列表框中選中和取消選中所有復選框?
<ListBox Height="168" HorizontalAlignment="Left" Margin="45,90,0,0" Name="listBox1" VerticalAlignment="Top" Width="120">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Name}" IsChecked="{Binding Ck, Mode=TwoWay}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
數據綁定是:
List<uu> xx = new List<uu>();
xx.Add(new uu { Name = "A", Ck = false });
xx.Add(new uu { Name = "A", Ck = false });
listBox1.ItemsSource = xx;
更新:
是否可以做這樣的事情:
foreach (ListBoxItem item in listBox1.Items)
{
CheckBox ch = (CheckBox)item;
ch.IsChecked = true;
}
需要考慮的幾件事。
1)首先使用ObservableCollection(首選)或BindingList而不是List作為數據源
2)確保在您的類上實現INotifyPropertyChanged。 在這里查看示例
3)現在您已正確設置了綁定設置,循環遍歷集合,並使用foreach或其他循環將checked屬性設置為false。 綁定系統將處理其余部分,並且列表中的更改將正確反映在用戶界面上
更新:添加了一個簡短的代碼示例
在您的代碼背后:
ObservableCollection<uu> list = new ObservableCollection<uu>();
MainWindow()
{
InitializeComponent();
// Set the listbox's ItemsSource to your new ObservableCollection
ListBox.ItemsSource = list;
}
public void SetAllFalse()
{
foreach (uu item in this.list)
{
item.Ck = false;
}
}
在uu類中實現INotifyPropertyChanged:
public class uu: INotifyPropertyChanged
{
private bool _ck;
public bool Ck
{
get { return _ck; }
set
{
_ck = value;
this.NotifyPropertyChanged("Ck");
}
}
private void NotifyPropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
通常,您將只使用數據綁定,如下所示。
List<uu> items = listbox1.ItemsSource as List<uu>();
foreach (var item in items)
item.Ck = true;
我從您的數據綁定中推斷出Ck
變量名稱,並從您的示例代碼中推斷出ItemsSource類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.