Reputation: 3619
I'm trying to figure out a way to bind my CheckBox
IsChecked
property. Basically, I have a list of items which the ListBox
is bound to. When a user checks the box, a command is invoked and that item is added to a collection.
However, what if I want to programmatically select items in the list? I would like the IsChecked
item to be based on whether or not the item exists in a list in the ViewModel.
In other words, if in my viewmodel, I do something like vm.MySelectedItems.Add(thisItem)
, I would like the CheckBox
to be Checked
.
Is this possible and if so, how should I go about it?
Thank you.
<ListBox.ItemTemplate>
<DataTemplate>
<WrapPanel>
<CheckBox IsChecked={Binding ???} />
<TextBlock VerticalAlignment="Center" Text="{Binding Converter={StaticResource nameConverter}}" />
</WrapPanel>
</DataTemplate>
</ListBox.ItemTemplate>
Upvotes: 2
Views: 6143
Reputation: 15823
Create a ViewModel for each item of your list. In your example: vm.MySelectedItems.Add(thisItem)
let's assume thisItem
is of type ListBoxItemViewModel
. This type should have a property called IsChecked
, and then in Xaml
<ListBox.ItemTemplate>
<!-- ViewModel: ListBoxItemViewModel -->
<DataTemplate>
<WrapPanel>
<CheckBox IsChecked={Binding IsChecked} />
<TextBlock VerticalAlignment="Center" Text="{Binding Converter={StaticResource nameConverter}}" />
</WrapPanel>
</DataTemplate>
</ListBox.ItemTemplate>
Hope I got your question properly :).
Cheers
Upvotes: 4