Reputation: 622
Am Using the checkbox in listbox items, how to Checked and Unchecked all checkboxes from the listbox?
<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>
DataBinding is :
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;
Update :
Is it possible to do something like this:
foreach (ListBoxItem item in listBox1.Items)
{
CheckBox ch = (CheckBox)item;
ch.IsChecked = true;
}
Upvotes: 0
Views: 2495
Reputation: 1269
A couple of things to consider.
1) First use an ObservableCollection (preferred) or a BindingList instead of a List as your datasource
2) Make sure you implement INotifyPropertyChanged on your class. See an example here
3) Now that you have your binding setup correctly, loop through the collection and set the checked property to false using a foreach or other loop. The binding system will handle the rest and the changes in your list will be properly reflected on the UI
UPDATE: Added a brief code example
In your code-behind:
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;
}
}
Implementing INotifyPropertyChanged in uu class:
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
}
Upvotes: 4
Reputation: 22148
You would typically just use databindings as demonstrated below.
List<uu> items = listbox1.ItemsSource as List<uu>();
foreach (var item in items)
item.Ck = true;
I am inferring the Ck
variable name from your databindings and the ItemsSource type from your sample code.
Upvotes: 1