让我用伪代码问这个问题:
<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>
哪里
"Contacts"将ViewModel对象设置为窗口的DataContext .
"Contacts"具有"PersonCollection",公共ICommand PersonSelectedCommand属性 . "PersonCollection"是List
"Person"有姓名,年龄属性
目前这不起作用,因为CheckBox试图找到并绑定对象“person”的ICommand“PersonSelectedCommand”属性,该属性不存在!
如何将CheckBox绑定到对象“Contact”的ICommand“PersonSelectedCommand”属性
感谢致敬
123Deveopler
3 回答
我喜欢SeeSharp的答案,但是要直接回答你的问题,你需要做的就是将CheckBox的Command绑定更改为:
只有当您需要更多控制而不是简单地绑定IsSelected属性时,这比SeeSharp的答案更可取 . 否则选择绑定IsSelected .
你能改变视图模型吗?如果你将Bool属性IsSelected添加到Person,我认为会更好 . 并将其绑定到复选框:
命令不是必需的,您可以在属性IsSelected的setter中添加一些功能 .
PersonSelectedCommand
必须位于Person范围内 . 因此,当您绑定到人员列表时,您将拥有一个命令列表 . 因此,无论何时选择某个人,您都将拥有相应的命令来执行 .另外,你可以在Binding中使用RelativeSource找到祖先,并以这种方式设置PersonSelectedCommand . 检查这个答案:Is there a simple way to specify a WPF databinding where the path is one "level" up?