如何命令参数传递给方法的ViewModel在WPF? [英] how to pass command parameter to method in ViewModel in WPF?

查看:430
本文介绍了如何命令参数传递给方法的ViewModel在WPF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过 CommandParameter 的方法在我的视图模型
如何做到这一点?

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;
    }
}

这是我在 meyhod视图模型,我想通过 CommandParameter 。我使用 CommandParameter 的按钮。

This is my meyhod in ViewModel that I want to pass CommandParameter. I use CommandParameter for button.

推荐答案

视图模型意味着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.

这篇关于如何命令参数传递给方法的ViewModel在WPF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆