将命令参数传递给 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;
}
}
这是我在 ViewModel
中的方法,我想传递 CommandParameter
.我使用 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屋!