gpt4 book ai didi

wpf - ListBox.ContextMenu 通过命令获取选定项

转载 作者:行者123 更新时间:2023-12-03 10:14:07 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Pass command parameter from the xaml

(2 个回答)


6年前关闭。




我有这个观点:

<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>

我想获取选定的项目(或单击的项目)并在我的命令方法中用它做一些事情。这是我的 ViewModel 的 Tor 和命令方法:
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 as command parameter in a button?

最佳答案

绑定(bind)不起作用,因为 ContextMenu exists outside of your control's visual tree ,因此它不可能找到 ListBox .事实上,我很惊讶它在没有通常的咒语的情况下调用您的命令来获取关联控件的数据上下文:

<ContextMenu DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}" >

无论如何,您可以使用 answer suggested here ,或者我可以建议一个替代实现:添加 SelectedPerson属性到您的 View 模型:
private Person selectedPerson;
public Person SelectedPerson
{
get { return selectedPerson; }
set
{
selectedPerson = value;
RaisePropertyChanged(); // or whatever your implementation is
}
}

您的 XAML 也很简单:

<ListView ItemsSource="{Binding Persons}" 
SelectedItem="{Binding SelectedPerson}">
<ListBox.ContextMenu>
<ContextMenu>
<MenuItem Header="EMail"
Command="{Binding WriteMailCommand}"
CommandParameter="{Binding SelectedPerson}" />
</ContextMenu>
</ListBox.ContextMenu>
</ListView>

关于wpf - ListBox.ContextMenu 通过命令获取选定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33548871/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com