如何选中和取消选中列表框中的已选框项目?

问题描述:

上午使用列表框项目中的复选框,如何选中和取消选中列表框中的所有复选框?如何选中和取消选中列表框中的已选框项目?

<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; 
     } 
+0

*设置* ItemsSource不完全是数据绑定。 –

一些事情要考虑。

1)首先使用一个ObservableCollection(首选)或一个的BindingList而不是列表作为数据源

2)确保你在你的类执行INotifyPropertyChanged。看一个例子here

3)现在你已经正确地设置了绑定,循环访问集合,并使用foreach或其他循环将checked属性设置为false。结合系统将处理其余部分,并在列表中的更改将正确地反映在UI

UPDATE:增加了一个简短的代码示例

在你的后台代码:

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 
} 
+0

robo有它的权利。看起来您已经正确设置了数据绑定,但确保您的项目实现INotifyPropertyChanged接口很重要。否则,您可以在代码中设置属性,但不会反映在用户界面上。 ObservableCollection 对确保ListBox知道何时从集合中添加或删除项目很重要,但它不应该影响复选框是否更改。 –

+0

+1是的,这个答案比我的更全面。这些是XAML绑定中的关键元素,在做这样的事情时应该被理解。 –

您通常只使用数据绑定,如下面所示。

List<uu> items = listbox1.ItemsSource as List<uu>(); 

foreach (var item in items) 
    item.Ck = true; 

我推断从数据绑定的Ck变量名,并从你的示例代码的ItemsSource类型。

+0

是否有可能做这种foreach(listBoxItems中的ListBoxItem项) { CheckBox ch =(CheckBox)item; ch.IsChecked = true; } – Vero009

+1

@ Vero009:你做不到这一点,你甚至不希望做到这一点。 –

+1

@ Vero009:如果您实施INotifyPropertyChanged,则不需要那样做。更改uu类对象上的值将通过您已经设置的绑定自动反映到UI中。无需尝试直接访问控制 – robowahoo