一、目的
降低代碼耦合度(降低UI層和BLL層的代碼耦合度),將UI層的后台代碼更好的轉移到BLL層中,讓視圖和業務邏輯分離的更好
二、使用方式
1.創建一個RelayCommand,繼承ICommand接口
public class RelayCommand : ICommand { #region Fields private readonly Func<Object, Boolean> _canExecute; private readonly Action<Object> _execute; #endregion #region Constructors public RelayCommand(Action<Object> execute) : this(execute, null) { } public RelayCommand(Action<Object> execute, Func<Object, Boolean> canExecute) { if (execute == null) throw new ArgumentNullException("execute"); _execute = execute; _canExecute = canExecute; } #endregion #region ICommand Members public event EventHandler CanExecuteChanged { add { if (_canExecute != null) CommandManager.RequerySuggested += value; } remove { if (_canExecute != null) CommandManager.RequerySuggested -= value; } } public Boolean CanExecute(Object parameter) { return _canExecute == null ? true : _canExecute(parameter); } public void Execute(Object parameter) { _execute(parameter); } #endregion }
2.創建一個ViewModel類,創建RelayCommand屬性對象
(1)使用lambda表達式
public class ViewModelTest { public ICommand ShowMessage { get { return new RelayCommand(new Action<Object>(t => { if (t == null) MessageBox.Show("not have param"); else MessageBox.Show(t.ToString()); })); } } }
(2)使用函數
public class ViewModelTest { private void UpdateNameExecute(Object parameter) { MessageBox.Show("haha"); } private bool CanUpdateNameExecute(Object parameter) { return true; } public ICommand ShowMessage { get { return new RelayCommand(UpdateNameExecute, CanUpdateNameExecute); } } }
3.界面后台類,將ViewModel對象賦給內容上下文
DataContext = new ViewModelTest();
4.界面綁定命名
(1)不帶參數
<Button Width="60" Height="30" Command="{Binding ShowMessage}"/>
(2)帶參數
<Button Width="60" Height="30" Command="{Binding ShowMessage}" CommandParameter="have param"/>
5.綁定命令的方式
(1) button類型的按鈕 直接用Command綁定
<Button Width="60" Height="30" Command="{Binding ShowMessage}"/>
(2) InputBindings.MouseBinding 鼠標事件綁定
例:
<Label Content="點擊我呀" HorizontalAlignment="Left" Height="23" Margin="243,256,0,0" VerticalAlignment="Top" Width="120"> <Label.InputBindings> <MouseBinding MouseAction="LeftClick" Command="{Binding CmdShow}"></MouseBinding> </Label.InputBindings> </Label>
MouseAction:
// 不執行任何操作。
None = 0,
// 單擊鼠標左鍵。
LeftClick = 1,
// 單擊鼠標右鍵。
RightClick = 2,
// 單擊鼠標按鈕。
MiddleClick = 3,
// 單次鼠標輪旋轉。
WheelClick = 4,
// 雙擊鼠標左鍵。
LeftDoubleClick = 5,
// 雙擊鼠標右鍵。
RightDoubleClick = 6,
// 雙擊鼠標按鈕。
MiddleDoubleClick = 7
(3)InputBindings.KeyBinding 鍵盤事件綁定
<Window.InputBindings> //按鍵A <KeyBinding Key="A" Command="{Binding CmdShow}"/> //按鍵Ctrl + B <KeyBinding Gesture="Ctrl + B" Command="{Binding CmdShow}"/> //按鍵Shift+C <KeyBinding Modifiers="Shift" Key="C" Command="{Binding CmdShow}"/> </Window.InputBindings>
key(enum Key):單個按鍵
Gesture:組合按鍵
Modeifers(enum ModifierKeys):指定修改鍵集 和key組合使用
public enum ModifierKeys
{
// 按下沒有任何修飾符。
None = 0,
// ALT 鍵。
Alt = 1,
// CTRL 鍵。
Control = 2,
// SHIFT 鍵。
Shift = 4,
// Windows 徽標鍵。
Windows = 8
}
參考:
https://www.cnblogs.com/weiweiboqi/p/4682136.html