在WPF中将命令参数传递给ViewModel中的方法? [英] Pass command parameter to method in ViewModel in WPF?
问题描述
我试图将CommandParameter
传递给我的ViewModel
中的方法.
该怎么做?
I am trying to pass CommandParameter
to the method in my ViewModel
.
How to do this?
private void Open(object sender)
{
if (sender==this.objMainWindow.btnHistory)
{
objMainWindow.Container.Child = objHistory;
}
if (sender == this.objMainWindow.btnNew_Item)
{
objMainWindow.Container.Child = objNewItem;
}
if (sender == this.objMainWindow.btnSide_Effects)
{
objMainWindow.Container.Child = objSideEffect;
}
}
这是我要通过CommandParameter
的ViewModel
中的方法.我将CommandParameter
用于按钮.
This is my meyhod in ViewModel
that I want to pass CommandParameter
. I use CommandParameter
for button.
推荐答案
"ViewModel"表示MVVM.如果您正在执行MVVM,则不应将视图传递到视图模型中.通常,您在XAML中执行以下操作:
"ViewModel" implies MVVM. If you're doing MVVM you shouldn't be passing views into your view models. Typically you do something like this in your XAML:
<Button Content="Edit"
Command="{Binding EditCommand}"
CommandParameter="{Binding ViewModelItem}" >
然后在您的视图模型中:
And then this in your view model:
private ViewModelItemType _ViewModelItem;
public ViewModelItemType ViewModelItem
{
get
{
return this._ViewModelItem;
}
set
{
this._ViewModelItem = value;
RaisePropertyChanged(() => this.ViewModelItem);
}
}
public ICommand EditCommand { get { return new RelayCommand<ViewModelItemType>(OnEdit); } }
private void OnEdit(ViewModelItemType itemToEdit)
{
... do something here...
}
显然,这只是为了说明这一点,如果只有一个要编辑的属性称为ViewModelItem,则无需将其作为命令参数传递.
Obviously this is just to illustrate the point, if you only had one property to edit called ViewModelItem then you wouldn't need to pass it in as a command parameter.
这篇关于在WPF中将命令参数传递给ViewModel中的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!