1

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

0

3 Answers 3

6

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
  • This is what I was looking for. My CheckBox is already has a binding for IsSelected property (I didn't mentioned in the question). And as you said I need more control. Thanks. Commented Jun 17, 2010 at 8:37
1

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.

1
  • Good answer (+1). Also see my answer, which addresses how he can do it without changing his ViewModel.
    – Ray Burns
    Commented Jun 17, 2010 at 6:35
0

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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.