tags:

views:

446

answers:

1

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>
+3  A: 

Hi Billb.

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

Anvaka
Thanks Anvaka, I thought of that as well, but felt there had to be a better way. If that's the best way, I'm happy to do it. Thank you for the response.
billb
I went with this approach, thanks for the answer!
billb
Glad I could help :)!
Anvaka