1:写一个类继承ICommand接口
public class MyCommand : ICommand { private readonly Action<object> executeAction; private readonly Func<object, bool> canExecuteAction; public event EventHandler CanExecuteChanged; public MyCommand(Action<object> executeAction) : this(executeAction, null) { } public MyCommand(Action<object> executeAction, Func<object, bool> canExecuteAction) { this.executeAction = executeAction; this.canExecuteAction = canExecuteAction; } public bool CanExecute(object parameter) { if (canExecuteAction != null) { return canExecuteAction((object)parameter); } return true; } public void Execute(object parameter) { if (CanExecute(parameter)) { executeAction((object)parameter); } } }
2:在ViewMode中定义一个Comand 返回一个自定义Command实例,传入方法
public class MainPageViewMode { public ICommand ShowHello { get { return new MyCommand(showhello); } } private void showhello(object param) { MessageBox.Show("Hello!"); } }
3:前台运用
<Button x:Name="addxap" Content="CommandTest" Command="{Binding ShowHello}" />
这样,点击按钮的时候就会执行ViewMode中的方法了。