MVVM开发模式MVVM Light Toolkit中使用事件和参数传递

本文介绍了MVVM模式下RelayCommand的使用方法,包括如何创建RelayCommand实例及实现命令参数传递。RelayCommand是MVVM框架中常用的一个类,用于在视图模型和视图间传递命令。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Light中定义了类GalaSoft.MvvmLight.Command.RelayCommand

这个类继承了ICommand方法,实现了其中的方法,Action就是一个方法参数

复制代码
// 摘要:     //     A command whose sole purpose is to relay its functionality to other objects     //     by invoking delegates. The default return value for the CanExecute method     //     is 'true'. This class does not allow you to accept command parameters in     //     the Execute and CanExecute callback methods.     public class RelayCommand : ICommand     {         // 摘要:         //     Initializes a new instance of the RelayCommand class that can always execute.          public RelayCommand(Action execute);         //         // 摘要:         //     Initializes a new instance of the RelayCommand class.          public RelayCommand(Action execute, Func<bool> canExecute);          // 摘要:         //     Occurs when changes occur that affect whether the command should execute.         public event EventHandler CanExecuteChanged;          // 摘要:         //     Defines the method that determines whether the command can execute in its         //     current state.          [DebuggerStepThrough]         public bool CanExecute(object parameter);         //         // 摘要:         //     Defines the method to be called when the command is invoked.          public void RaiseCanExecuteChanged();     }
复制代码

做一个简单的导航事件

从MainView导航到View1,

在View1的Viewmodel中定义这个事件属性

 public RelayCommand GotoView1
        {
            get;
            set;
        }

在构造函数中赋值给GotoView1

 GotoView1 = new RelayCommand(delegate {
                System.Windows.MessageBox.Show("Go to View1");
            });

//或者定义一个单独的方法  GotoView1 = new RelayCommand( ()=>GoToView1());

然后在MainPage.xaml中绑定事件

  <HyperlinkButton x:Name="View1" Grid.Row="1" Content="Go to View1" Command="{Binding GotoView1}" ></HyperlinkButton>

 

参数传递。

定义事件的时候很多情况下都需要传入参数,MVVM light也有这功能,而且 比较简单,方式如下:

//<string>这个就是GotoView1方法需要的参数,参数类型是string,当然可以根据需要变成其他类型,实体类型都可以
复制代码

public RelayCommand<string> GotoView1 { get; set; }

  public void GoToView11(string msg)
  {
         System.Windows.MessageBox.Show(msg + "Go to View1");
  }

//对这个方法属性赋值,test只是形式参数,无任何意义,意思是把字符串类型的test传递给GotoView方法
GotoView1 = new RelayCommand<string>((test) => GoToView11(test));


复制代码

页面上绑定这个方法的时候可以指定CommandParameter来指定Command的绑定方法的参数,如果类型是字符串,直接="字符串"就可以

如果是其他实体类型可以参考使用Binding语法CommandParameter="{Binding SelectedItem, ElementName=集合控件}"

            <HyperlinkButton x:Name="View1" Grid.Row="1" Content="Go to View1" Command="{Binding GotoView1}" CommandParameter="Hello" ></HyperlinkButton>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值