MVVM开发模式MVVM Light Toolkit中使用事件和参数传递
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>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
2011-08-24 Windows Server 2003文件夹不能共享的解决办法【转】
2008-08-24 对美国转嫁次贷危机的思考