帮助将命令参数绑定到相关源
我有一个 ListBox
,我已添加了 ContextMenu
到其中。我希望将 ContextMenu 中的一项绑定到命令,并且希望传递给该命令的参数成为 ListBox 控件当前选定的项。这是我的 xaml:
<ListBox x:Name="selectedVascularBeds"
ItemsSource="{Binding Path=UserSelectedVascularBeds}"
dd:DragDrop.IsDropTarget="True"
dd:DragDrop.DropHandler="{Binding}"
DisplayMemberPath="VascularBedName">
<ListBox.ContextMenu>
<ContextMenu>
<MenuItem Header="Remove" Command="{Binding Path=RemoveSelectedVascularBedCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource
Mode=FindAncestor,
AncestorType={x:Type ListBox}},
Path=SelectedItem}"/>
</ContextMenu>
</ListBox.ContextMenu>
</ListBox>
此 ListBox
是绑定到视图模型对象的用户控件的一部分。我对底层对象的命令方法被调用,但传入的参数始终为空。
我已经测试过将 CommandParameter
的绑定更改为简单的 {Binding}
,这会导致用户控件的数据上下文被传递到我的方法中 - 所以我知道该命令正在工作并正确传递参数。我似乎无法获得正确的绑定来访问 ListBox
的 SelectedItem
属性。
帮助?
I have a ListBox
that I have added a ContextMenu
to. I want one of the items in the ContextMenu
to be bound to a command and I want the parameter passed to that command to be the currently selected item of the ListBox
control. Here's my xaml:
<ListBox x:Name="selectedVascularBeds"
ItemsSource="{Binding Path=UserSelectedVascularBeds}"
dd:DragDrop.IsDropTarget="True"
dd:DragDrop.DropHandler="{Binding}"
DisplayMemberPath="VascularBedName">
<ListBox.ContextMenu>
<ContextMenu>
<MenuItem Header="Remove" Command="{Binding Path=RemoveSelectedVascularBedCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource
Mode=FindAncestor,
AncestorType={x:Type ListBox}},
Path=SelectedItem}"/>
</ContextMenu>
</ListBox.ContextMenu>
</ListBox>
This ListBox
is part of a user control that is bound to a view model object. My command method on the underlying object gets called but the parameter passed in is always null.
I have tested changing the binding of the CommandParameter
to simply {Binding}
which results in the user control's data context being passed into my method - so I know that the command is working and passes parameters correctly. I just can't seem to get the correct binding to access the ListBox
's SelectedItem
property.
Help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
上下文菜单不是列表框的后代。尝试使用元素名称绑定
the context menu is not a descendant of the list box. try an element name binding instead
ElementName 绑定也不起作用,参数仍然为空,我在控制台输出中发现了错误:
搜索该错误将我带到此链接,但看起来上下文菜单不同,我无法按照我的方式实现我想要的目标。
ContextMenu 中 MenuItem 的 ElementName 绑定
The ElementName binding also didn't work, the parameter was still null and I found an error in the console output:
Searching for that error lead me to this link though and it looks like the Context menu is different and I can't achieve what I want the way I'm going about it.
ElementName Binding from MenuItem in ContextMenu