一、动态绑定ItemSource的MenuItem如何绑定事件并传入参数
<Menu DockPanel.Dock="Top"> <MenuItem Header="A"> <MenuItem Header="B1"/> <MenuItem Header="B2"/> <MenuItem Header="B3"/> <MenuItem ItemsSource="{Binding Commands}" Header="B4"> <MenuItem.ItemContainerStyle> <Style TargetType="{x:Type MenuItem}"> <Setter Property="Header" Value="{Binding Path=Text}" /> <Setter Property="Command" Value="{Binding Path=Command}" /> <Setter Property="CommandParameter" Value="{Binding Path=Parameter}" /> </Style> </MenuItem.ItemContainerStyle> </MenuItem> </MenuItem> </Menu>
ViewModel:
添加引用:Microsoft.Practices.Prism
public class NotifyPropertyBase : INotifyPropertyChanged { public void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } [field: NonSerialized] public event PropertyChangedEventHandler PropertyChanged; } public class MenuViewModel : NotifyPropertyBase { public ICommand GoCommand { get; private set; } private List<MyCommand> _commands = new List<MyCommand>(); public List<MyCommand> Commands { get { return _commands; } } public MenuViewModel() { GoCommand = new DelegateCommand<object>(OnGoCommand); LoadCommands(); } private void LoadCommands() { //数据绑定 for (int i = 0; i < 5; i++) { //Parameter就是子菜单的文本名称,点击时触发 MyCommand c1 = new MyCommand { Command = GoCommand, Parameter = string.Format("MenuName{0}", i), Text = string.Format("MenuName{0}", i) }; _commands.Add(c1); } } /// <summary> /// 功能函数 /// </summary> /// <param name="obj">传入子菜单项的Parameter值</param> private void OnGoCommand(object obj) { string GetName = (string)obj; MessageBox.Show(GetName); } } public class MyCommand { //名称可以改但要与界面绑定一致 public ICommand Command { get; set; } public string Text { get; set; } public string Parameter { get; set; } }
参考链接:http://cn.voidcc.com/question/p-ufqvonpj-gs.html
https://blog.csdn.net/weixin_30322405/article/details/99837992/
标签:set,string,get,Menu,汇总,new,WPF,Parameter,public From: https://www.cnblogs.com/Mars-0603/p/17076838.html