wpf mvvm MenuItem的Command事件
生活随笔
收集整理的這篇文章主要介紹了
wpf mvvm MenuItem的Command事件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
這是一個事件的輔助類,可以通過它實現MenuItem的Command事件
public class MyCommands : Freezable, ICommand, ICommandSource{public MyCommands() {}public static readonly DependencyProperty CommandParameterProperty =DependencyProperty.Register("CommandParameter",typeof(object),typeof(MyCommands),new PropertyMetadata((object)null));public object CommandParameter{get{return (object)GetValue(CommandParameterProperty);}set{SetValue(CommandParameterProperty, value);}}public static readonly DependencyProperty CommandTargetProperty =DependencyProperty.Register("CommandTarget",typeof(IInputElement),typeof(MyCommands),new PropertyMetadata((IInputElement)null));public IInputElement CommandTarget{get{return (IInputElement)GetValue(CommandTargetProperty);}set{SetValue(CommandTargetProperty, value);}}public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(MyCommands), new PropertyMetadata(new PropertyChangedCallback(OnCommandChanged)));public ICommand Command{get { return (ICommand)GetValue(CommandProperty); }set { SetValue(CommandProperty, value); }}#region ICommand Memberspublic bool CanExecute(object parameter){if (Command != null)return Command.CanExecute(CommandParameter);return false;}public void Execute(object parameter){Command.Execute(CommandParameter);}public event EventHandler CanExecuteChanged;private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e){MyCommands commandReference = d as MyCommands;ICommand oldCommand = e.OldValue as ICommand;ICommand newCommand = e.NewValue as ICommand;if (oldCommand != null){oldCommand.CanExecuteChanged -= commandReference.CanExecuteChanged;}if (newCommand != null){newCommand.CanExecuteChanged += commandReference.CanExecuteChanged;}}#endregion#region Freezableprotected override Freezable CreateInstanceCore(){throw new NotImplementedException();}#endregion}在xaml中調用的方法
<UserControl.Resources><unititys:MyCommands x:Key="aaa" Command="{Binding Path=aaa}"/> </UserControl.Resources><ContextMenu x:Key="RouterMenu1" DataContext="{Binding RelativeSource={RelativeSource Mode=Self}, Path=PlacementTarget.DataContext}"><MenuItem Header="調用aaa" Command="{StaticResource aaa}"></MenuItem></ContextMenu>在ViewModel中和普通的Command一樣的調用就行了
轉載于:https://www.cnblogs.com/chenjinshi/p/4645081.html
總結
以上是生活随笔為你收集整理的wpf mvvm MenuItem的Command事件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: tcp测试软件app源码,Packet
- 下一篇: 数据结构(严蔚敏)视频百度云