I have a listbox and I have set the itemstemplate as shown below.
XAML:
<ListBox ItemsSource="{Binding DataList}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox x:Name="CheckBox" HorizontalAlignment="Center" VerticalAlignment="Center" />
<TextBlock x:Name="TextBlock" Text="{Binding Title}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="10,0,0,10" FontSize="26.667" TextWrapping="Wrap"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I want to get which all check box has been selected.Is there any way to get checkbox control for each item so that I can check its IsChecked
property.
I can think of a way of binding the IsChecked property.But Is there any other way to do it?
Yes. One way to do is to bind the IsChecked property. And if you are using MVVM, probably that's the right way to do it.
Anyways, if you don't want to go the binding way, and assuming you want to iterate over all items of listbox, and prepare a list of checked items, see if this helps:
WPF - Find a Control from DataTemplate in WPF
If you're already binding to the Title property in the item template then it would certainly make sense to bind to IsChecked, too.
If you really need to, you can walk the visual tree by using the VisualTreeHelper
to find the CheckBox
instances.
Binding the IsChecked
property to a boolean property on your object instance contained within DataList
would be the simplest and cleanest way. Alternatively, if you want to avoid code behind, then you could write an attached property.
See also How to access a specific item in a Listbox with DataTemplate?
I bet it cannot be simpler than that:
<ListBox SelectionMode="Multiple" >
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox
IsChecked="{Binding Path=IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}"
Content="{Binding Path=Content, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>