如何在视图模型中创建多个命令(WPF,MVVM模式) [英] How to create multiple commands in a viewmodel ( WPF, MVVM Pattern )
本文介绍了如何在视图模型中创建多个命令(WPF,MVVM模式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的项目在中有一个viewmodel类我继承了RelayCommand 和 ICommand。
名为ExecuteCommand 的命令在 查看模型 如下所示和 工作正常。
public 类LoginWindowViewModel:WorkSpaceViewModel
{
RelayCommand _executecommand;
public ICommand ExecuteCommand
{
get
{
if (_executecommand == null )
{
_executecommand = new RelayCommand(param => 执行(),param => CanExecute());
}
return _executecommand;
}
}
public virtual void 执行 ()
{
MainWindow window = new MainWindow();
window.Show();
}
public virtual bool CanExecute()
{
返回 true;
}
}
我的问题 ,我怎么能创建另一个命令 相同的视图模型和 使用。
解决方案
简单。只需创建另一个
ICommand
属性:RelayCommand _executecommand2;
public ICommand ExecuteCommand2
{
get
{
if (_executecommand2 == null )
{
_executecommand2 = new RelayCommand(param = > Execute2(),param = > CanExecute2());
}
return _executecommand2;
}
}
public virtual void Execute2()
{
MainWindow window = new MainWindow();
window.Show();
}
public virtual bool CanExecute2()
{
return true ;
}使用它时,您只需将
ICommand
属性绑定到命令
视图元素的属性。类似于:< 按钮 命令 = < span class =code-keyword> {Binding ExecuteCommand2} / > 跨度>
My project has a viewmodel class in which I have inherited RelayCommand and ICommand.
A Command called ExecuteCommand is created in this view model as shown below and is working fine.
public class LoginWindowViewModel:WorkSpaceViewModel
{
RelayCommand _executecommand;
public ICommand ExecuteCommand
{
get
{
if (_executecommand == null)
{
_executecommand = new RelayCommand(param => Execute(),param => CanExecute());
}
return _executecommand;
}
}
public virtual void Execute()
{
MainWindow window = new MainWindow();
window.Show();
}
public virtual bool CanExecute()
{
return true;
}
}
My question is, how can I create another command in the same view model and how to use it.
解决方案
Simple. Just create another
ICommand
property:RelayCommand _executecommand2; public ICommand ExecuteCommand2 { get { if (_executecommand2 == null) { _executecommand2 = new RelayCommand(param => Execute2(), param => CanExecute2()); } return _executecommand2; } } public virtual void Execute2() { MainWindow window = new MainWindow(); window.Show(); } public virtual bool CanExecute2() { return true; }For using it, you can just bind the
ICommand
property to theCommand
property of your view''s element. Something like:<Button Command="{Binding ExecuteCommand2}" />
这篇关于如何在视图模型中创建多个命令(WPF,MVVM模式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文