RelayCommand命令
原文:http://www.cnblogs.com/xiepeixing/archive/2013/08/13/3255152.html
?
常用Wpf開(kāi)發(fā)中我們?cè)赩iewModel中實(shí)現(xiàn)INotifyPropertyChanged接口,通過(guò)觸發(fā)PropertyChanged事件達(dá)到通知UI更改的目的;
在MVVMLight框架里,這里我們定義的ViewModel都繼承自ViewModelBase,ViewModelBase封裝在MvvmLight框架中,它已經(jīng)實(shí)現(xiàn)了INotifyPropertyChanged接口,
因此我們?cè)诙xViewModel屬性時(shí),只需要調(diào)用RaisePropertyChanged(PropertyName)就可以進(jìn)行屬性更改通知了。
?
?事件是WPF/SL應(yīng)用程序中UI與后臺(tái)代碼進(jìn)行交互的最主要方式,與傳統(tǒng)方式不同,mvvm中主要通過(guò)綁定到命令來(lái)進(jìn)行事件的處理,因此要了解mvvm中處理事件的方式,就必須先熟悉命令的工作原理。
一、RelayCommand命令
WPF/SL命令是通過(guò)實(shí)現(xiàn)?ICommand?接口創(chuàng)建的。?ICommand?公開(kāi)兩個(gè)方法(Execute?及?CanExecute)和一個(gè)事件(CanExecuteChanged)。?Execute?執(zhí)行與命令關(guān)聯(lián)的操作。CanExecute?確定是否可以在當(dāng)前命令目標(biāo)上執(zhí)行命令。在MvvmLight中實(shí)現(xiàn)ICommand接口的類是RelayCommand,RelayCommand通過(guò)構(gòu)造函數(shù)初始化Execute?和?CanExecute方法,因此,構(gòu)造函數(shù)傳入的是委托類型的參數(shù),Execute?和?CanExecute則執(zhí)行的是委托的方法,RelayCommand相關(guān)代碼如下:
public RelayCommand(Action execute, Func<bool> canExecute){if (execute == null){throw new ArgumentNullException("execute");}_execute = execute;_canExecute = canExecute;}[DebuggerStepThrough]public bool CanExecute(object parameter){return _canExecute == null ? true : _canExecute();}public void Execute(object parameter){_execute();}二、 Comand屬性綁定
簡(jiǎn)單的例子:一個(gè)TextBox和一個(gè)Button,TextBox非空內(nèi)容時(shí)候Button才可用,可用的Button點(diǎn)擊后把TextBox內(nèi)容show出來(lái)。
<Window x:Class="MVVMLightDemo.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:local="clr-namespace:MVVMLightDemo.ViewModel"Title="MainWindow" Height="350" Width="525"><Window.DataContext><local:MainWindowViewModel></local:MainWindowViewModel></Window.DataContext><Grid><StackPanel><TextBox Text="{Binding UserName, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></TextBox><Button Content="show" Command="{Binding ShowCommand}" CommandParameter="{Binding UserName}"></Button></StackPanel></Grid> </Window>ViewMode:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; // using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using System.Windows.Input; using System.Windows; namespace MVVMLightDemo.ViewModel {public class MainWindowViewModel:ViewModelBase{private string _UserName;public string UserName{get { return _UserName; }set { _UserName = value; RaisePropertyChanged("UserName"); }}public ICommand ShowCommand{get{ return new RelayCommand<string>((user) => {MessageBox.Show(user);}, (user) =>{return !string.IsNullOrEmpty(user);});}}} }轉(zhuǎn)載于:https://www.cnblogs.com/xcsn/p/4454210.html
總結(jié)
以上是生活随笔為你收集整理的RelayCommand命令的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 网关和网段理解资料
- 下一篇: 获取存储过程返回值及代码中获取返回值