简体   繁体   中英

How to bind the Command property of the ItemTemplate CheckBox to ViewModel object's property?

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

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.

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM