SL4:将视图中的元素作为参数传递给 ViewModel 中的命令
我们有一个用户控件,其子控件之一上带有上下文菜单。
该命令绑定到 ViewModel 中的 RelayCommand。
但是,该命令必须作用于视图中的另一个子控件。
最好的方法是什么?我尝试过将所需的子控件作为参数传递,但我认为语法不正确:
<Controls:ContextMenu >
<Controls:MenuItem Header="Center" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click" >
<GalaSoft_MvvmLight_Command:EventToCommand
Command="{Binding RecenterCommand}"
CommandParameter="{Binding ElementName=scrollViewer}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Controls:MenuItem>
</Controls:ContextMenu>
命令:
RecenterCommand = new RelayCommand<ScrollViewer>(Recenter);
private void Recenter(ScrollViewer obj)
{
}
当我使用上下文菜单时,调用Recenter(),但 obj 参数为空。
CommandParameter 绑定中 ElementName 属性的正确语法是什么?
更新:我尝试将 CommandParameter 更改为:
CommandParameter="{Binding ElementName=LayoutRoot, Path=scrollViewer}"
...但仍然不起作用。
感谢您的任何见解......
We have a user control with context menu on one of its child controls.
The Command is bound to a RelayCommand in the ViewModel.
However, the command has to act on another child control in the View.
What is the best way to do this? I have tried passing the desired child control as a parameter, but I think the syntax is incorrect:
<Controls:ContextMenu >
<Controls:MenuItem Header="Center" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click" >
<GalaSoft_MvvmLight_Command:EventToCommand
Command="{Binding RecenterCommand}"
CommandParameter="{Binding ElementName=scrollViewer}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Controls:MenuItem>
</Controls:ContextMenu>
The command:
RecenterCommand = new RelayCommand<ScrollViewer>(Recenter);
private void Recenter(ScrollViewer obj)
{
}
When I use the context menu, Recenter() is called, but the obj param is null.
What is the correct syntax for the ElementName attribute in the CommandParameter binding?
UPDATE: I tried changing the CommandParameter to:
CommandParameter="{Binding ElementName=LayoutRoot, Path=scrollViewer}"
...but still doesn't work.
Thanks for any insights....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您需要添加 PassEventArgsToCommand="True" 因此,代码将如下所示:
如果您想在代码隐藏中放置数据(这是我用于上下文菜单项的程序之一的代码)
SelectedEmployer e = ((MenuItem)e).DataContext as Employer
我希望这能解决您的问题,因为您给了我如何解决我的问题之一的提示..
I think that you need to add PassEventArgsToCommand="True" so, the code will be like this:
and if you want to cath the data in codebehind put (this is code from one of my programs used for a context menu item)
SelectedEmployer e = ((MenuItem)e).DataContext as Employer
I hope this will solve your problem, because you gave me a hint in how to solve one of my problems..