【发布时间】:2016-04-10 09:51:00
【问题描述】:
当试图传递xaml中的控件时,我们编写如下代码:
<MenuItem x:Name="NewMenuItem" Command="{Binding MenuItemCommand}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type MenuItem}}}" />
我正在尝试以编程方式创建MenuItem,如下所示:
var pluginMenuItem = new MenuItem
{
Header = "NewMenuItem,
Command = MenuItemCommand,
CommandParameter = "{Binding RelativeSource= {RelativeSource Mode=FindAncestor, AncestorType={x:Type MenuItem}}}"
};
这会将string "{Binding RelativeSource= {RelativeSource Mode=FindAncestor, AncestorType={x:Type MenuItem}}}" 作为CommandParameter 传递。
我错过了什么?
【问题讨论】:
-
语法是
XAML markup extension,不能在C#代码中使用。查找父元素,可以在代码中使用VisualTreeHelper类 -
在 ViewModel 中使用
VisualTreeHelper违反了 MVVM 模式,就像使用MenuItem一样。两者分别在 PresentationCore.dll 和 Presentation.dll 中定义
标签: c# wpf mvvm command commandparameter