ListBox.ContextMenu 通过命令获取所选项目 [英] ListBox.ContextMenu Get Selected Item via Command
问题描述
我有这个视图:
<StackPanel>
<StackPanel.DataContext>
<local:MainViewModel />
</StackPanel.DataContext>
<ListView ItemsSource="{Binding Persons}" x:Name="xamlPersonList">
<ListBox.ContextMenu>
<ContextMenu>
<MenuItem Header="EMail" Command="{Binding WriteMailCommand}" CommandParameter="{Binding ElementName=xamlPersonList,Path=SelectedItem}" />
</ContextMenu>
</ListBox.ContextMenu>
</ListView>
</StackPanel>
我想获取选定的项目(或点击的项目)并在我的命令方法中用它做一些事情.这是我的 Ctor 和我的 ViewModel 的命令方法:
I want to get the selected item (or the clicked item) and do some stuff with it inside my Command-Method. This is my Ctor and Command-Method of my ViewModel:
public ICommand WriteMailCommand { get; private set; }
public MainViewModel()
{
_persons = new ObservableCollection<Person>();
for (int i = 0; i < 10; i++)
{
_persons.Add(new Person()
{
ID = i,
Name = "Robert " + i
});
}
WriteMailCommand = new RelayCommand<object>(WriteMailMethod);
}
private void WriteMailMethod(object obj)
{
}
obj 参数始终为空.我不知道我在这里缺少什么?!我试过这个解决方案:How to pass listbox selecteditem作为按钮中的命令参数?
The obj parameter is always null. I don't know what I am missing here?! I tried this solution: How to pass listbox selecteditem as command parameter in a button?
推荐答案
绑定不起作用,因为 ContextMenu
存在于控件的可视化树之外,因此它不可能找到ListBox
.事实上,我很惊讶它在没有通常的咒语的情况下调用您的命令来获取关联控件的数据上下文:
The binding isn't working because the ContextMenu
exists outside of your control's visual tree, and so it's impossible for it to find the ListBox
. In fact I'm surprised it's invoking your command without the usual incantation to get the data context of the associated control:
<ContextMenu DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}" >
无论如何,您可以使用此处建议的答案,或者我可以建议替代实现:添加 SelectedPerson
属性添加到您的视图模型:
Regardless, you can use the answer suggested here, or I can suggest an alternate implementation: add a SelectedPerson
property to your view-model:
private Person selectedPerson;
public Person SelectedPerson
{
get { return selectedPerson; }
set
{
selectedPerson = value;
RaisePropertyChanged(); // or whatever your implementation is
}
}
您的 XAML 也很简单:
Your XAML would be simple, too:
<ListView ItemsSource="{Binding Persons}"
SelectedItem="{Binding SelectedPerson}">
<ListBox.ContextMenu>
<ContextMenu>
<MenuItem Header="EMail"
Command="{Binding WriteMailCommand}"
CommandParameter="{Binding SelectedPerson}" />
</ContextMenu>
</ListBox.ContextMenu>
</ListView>
这篇关于ListBox.ContextMenu 通过命令获取所选项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!