1
votes

Let me ask this question with a pseudo code:



<Window>
    <ListView ItemsSource="{Binding PersonCollection}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding Path=Name}" />
                    <TextBlock Text="{Binding Path=Age}" />
                    <TextBlock Text="/" />
                    <CheckBox Command="{Binding PersonSelectedCommand}" />  <!-- Where "PersonSelectedCommand" is a public command property available in ViewModel object (lets say "Contacts"  in this context)-->
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Window>

Where
"Contacts" the ViewModel object set as the DataContext for the window.

"Contacts" has "PersonCollection" , public ICommand PersonSelectedCommand properties. "PersonCollection" is List

"Person" has Name, Age properties

Currently this is not working as CheckBox is trying to find and bind the ICommand "PersonSelectedCommand" property of object "person", which does not exists!

How will bind the CheckBox to the ICommand "PersonSelectedCommand" property of object "Contact"

Thanks and regards
123Deveopler

3

3 Answers

6
votes

I liked SeeSharp's answer, but to directly answer your question, all you need to do is change your CheckBox's Command binding to:

Command="{Binding DataContext.PersonSelectedCommand,
                  RelativeSource={RelativeSource FindAncestor,ListView,1}}"

This is preferable to SeeSharp's answer only when you need more control than simply binding the IsSelected property will give you. Otherwise go with binding IsSelected.

1
votes

Can you change view model? I think will be better, if you add bool property IsSelected to Person. And bind it to checkbox:

<CheckBox IsChecked="{Binding IsSelected}"/>

Command is not requared and you can add some functionality in setter of property IsSelected.

0
votes

The PersonSelectedCommand has to be in the Person scope. So you'll have a list of commands when you bind to a list of persons. Hence whenever a person is selected, you will have the corresponding command to be executed.

Else you can find out the Ancestor using RelativeSource in Binding and set the PersonSelectedCommand that way. Check this answer: Is there a simple way to specify a WPF databinding where the path is one "level" up?