WPF MvvmLight RelayCommand 绑定Command 的使用

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

猜你喜欢

转载自www.cnblogs.com/cmblogs/p/9047066.html