尝试在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
传递。
我错过了什么?
答案 0 :(得分:1)
您可以使用下面提到的代码
来实现你的xaml代码看起来像
<Menu Name="menu" ItemsSource="{Binding MenuList,Mode=TwoWay}">
</Menu>
您的ViewModel看起来像
public class MainViewModel : ViewModelBase
{
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
MenuList.Add(new MenuItem()
{
Header = "MenuItem1",
Command = MenuItemCommand,
CommandParameter = "FirstMenu"
});
MenuList.Add(new MenuItem()
{
Header = "MenuItem2",
Command = MenuItemCommand,
CommandParameter = "SecondMenu"
});
}
private ObservableCollection<MenuItem> _menuList;
public ObservableCollection<MenuItem> MenuList
{
get { return _menuList ?? (_menuList = new ObservableCollection<MenuItem>()); }
set { _menuList = value; RaisePropertyChanged("MenuList"); }
}
private RelayCommand<string> _MenuItemCommand;
public RelayCommand<string> MenuItemCommand
{
get { return _MenuItemCommand ?? (_MenuItemCommand = new RelayCommand<string>(cmd)); }
set { _MenuItemCommand = value; }
}
private void cmd(string value)
{
MessageBox.Show(value);
}
}