標籤:操作 doc href element val model code path 邏輯
RelayCommand
Mvvm最大的特點就是分離了View和ViewModel,將資料的顯示和商務邏輯分開。使用WPF的Binding,我們不僅能夠
將資料從ViewModel綁定到View,同時也可以將行為綁定到View。例如,在主介面上點擊一個按鈕,這個按鈕實際完成
的操作是ViewModel中對應的方法。這裡我們用到Mvvm架構中的RelayCommand。下面是幾種常用的情況
不帶參數的RelayCommand
點擊按鈕,彈出訊息框
AppView.xaml
<Grid> <Button Width="100" Height="30" Command="{Binding ShowMsgCommand}"></Button></Grid>
AppViewModel.cs
/// <summary> /// 顯示訊息命令 /// </summary> public RelayCommand ShowMsgCommand { get; set; } public AppViewModel() { //初始化命令 ShowMsgCommand= new RelayCommand(ShowMsg); } /// <summary> /// 命令具體實現 /// </summary> private void ShowMsg() { MessageBox.Show("HelloWorld!"); }
帶參數的RelayCommand
點擊按鈕,顯示我們輸入的文本
AppView.xaml
<Grid> <TextBox x:Name="txt" Width="100" Height="30"></TextBox> <Button Width="100" Height="30" Command="{Binding ShowTxtCommand}" CommandParameter="{Binding ElementName=txt,Path=Text}" Margin="0,100,0,0"></Button></Grid>
AppViewModel.cs
/// <summary> /// 顯示訊息命令 /// </summary> public RelayCommand<string> ShowTxtCommand { get; set; } public AppViewModel() { //初始化命令 ShowTxtCommand = new RelayCommand<string>(ShowMsg); } /// <summary> /// 命令具體實現 /// </summary> private void ShowMsg(string txt) { MessageBox.Show(txt); }
RelayCommand是否可執行
注意,這是一個非常有用的功能,當RelayCommand執行的條件不滿足時,將會導致介面上的按鈕是禁用的。條件的判斷
是由WPF程式自動執行的,並且頻率非常高,所以,判斷是否可執行檔代碼應該盡量簡單。
AppView.xaml
<Grid> <TextBox x:Name="txt" Width="100" Height="30" Text="{Binding Txt,UpdateSourceTrigger=PropertyChanged}"></TextBox> <Button Width="100" Height="30" Command="{Binding ShowTxtCommand}" Margin="0,100,0,0"></Button></Grid>
AppViewModel.cs
private string _txt; /// <summary> /// 綁定到介面的Txt /// </summary> public string Txt { get { return _txt; } set { _txt = value; RaisePropertyChanged(() => Txt); } } /// <summary> /// 顯示訊息命令 /// </summary> public RelayCommand ShowTxtCommand { get; set; } public AppViewModel() { //初始化命令 ShowTxtCommand = new RelayCommand(ShowMsg, CanShowMsgExecute); } /// <summary> /// 命令具體實現 /// </summary> private void ShowMsg() { MessageBox.Show(Txt); } /// <summary> /// 顯示訊息命令是否可以執行 /// </summary> /// <returns></returns> private bool CanShowMsgExecute() { return !string.IsNullOrEmpty(Txt); }
注意:如果你使用的是.Net4.5,那麼介面上的按鈕可能禁用不到,這是Mvvm中的一個bug,不過作者已經修複了,解決
方案看這裡.
RelayCommand的使用就是這麼簡單。
http://www.cnblogs.com/HelloMyWorld/p/4750062.html
WPF MvvmLight RelayCommand 綁定Command 的使用