Reputation: 1555
I have a list box whose items are represented as check box as under
<ListBox Height="237" HorizontalAlignment="Center" Name="listBox1" VerticalAlignment="Top" Width="150" Margin="0,10,0,0" >
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox>
</CheckBox>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The itemssource is assigned in the code behind
listBox1.ItemsSource = names;
The GUI displays correct number of check boxes but with no text. How can I put the "content" of the checkboxes as in my itemssource of the listbox1?
Also how can I retrieve which checkboxes the user has checked in code behind?
Upvotes: 1
Views: 1487
Reputation: 10612
<ListBox.ItemTemplate>
<DataTemplate DataType="ListBoxItem">
<CheckBox Content="{Binding name}" IsChecked="{Binding isChecked}"/>
</DataTemplate>
</ListBox.ItemTemplate>
.
public MainWindow()
{
InitializeComponent();
List<MyListBoxItem> names = new List<MyListBoxItem>();
names.Add(new MyListBoxItem("salim", true));
listBox1.ItemsSource = names;
}
void getCheckedNames()
{
for (int i = 0; i < listBox1.Items.Count; i++)
{
if (((MyListBoxItem)listBox1.Items[i]).isChecked)
{
// Do things..
}
}
}
class MyListBoxItem
{
public string name { get; set; }
public bool isChecked { get; set; }
public MyListBoxItem(string name, bool isChecked)
{
this.name = name;
this.isChecked = isChecked;
}
}
Upvotes: 1
Reputation: 2970
Add binding to Checkbox like
<ListBox Height="237" HorizontalAlignment="Center" Name="listBox1" VerticalAlignment="Top" Width="150" Margin="0,10,0,0" >
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content={Binding}>
</CheckBox>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And when u need to get checkcbox which is checked hook Checked
event in XAML like
<DataTemplate>
<CheckBox Content={Binding} Checked="OnChecked" Unchecked="OnUnchecked">
</CheckBox>
</DataTemplate>
code behind: in that case sender is your CheckBox
private List _checked;
private void OnChecked(object sender, RoutedEventArgs e)
{
_checked.Add((CheckBox)sender);
}
private void OnUnchecked(object sender, RoutedEventArgs e)
{
_checked.Remove((CheckBox)sender);
}
Upvotes: 3