是否可以在视图模型中使用MVVM模式更改属性时在视图中执行方法?

时间:2013-05-05 07:06:32

标签: c# wpf mvvm

我想在我的应用程序中打开一个对话框,我希望在视图模型中的属性发生更改时关闭视图。

所以我在思考:

1.-在我的view.axml.cs(后面的代码)我有一个名为close()的方法,它执行视图的close方法。

2.-在我的视图模型中,我有一个名为ViewModelClosing的属性,bool

3.-视图,在某种程度上,我真的不知道如何,需要绑定视图模型的属性,并在属性更改时执行后面的代码中的方法。

有可能吗?

1 个答案:

答案 0 :(得分:2)

ÁlvaroGarcía

最简单的IMO最好的方法是从控制器接受ViewModel中的ICommand。

由于ViewModel不应该依赖于View或ViewController,因此下面的解决方案使用依赖注入/控制反转。

DelegateCommand(又名RelayCommand)是ICommand的包装器

我将代码保持在最低限度,专注于解决方案。

public class ViewController
{
    private View _view;
    private ViewModel _viewModel;

    public ViewController()
    {
        ICommand closeView = new DelegateCommand(m => closeView());
        this._view = new View();
        this._viewModel = new ViewModel(closeView);
        this._view.DataContext = this._viewModel;
    }

    private void closeView()
    {
        this._view.close();
    }
}

public class ViewModel
{
    private bool _viewModelClosing;

    public ICommand CloseView { get;set;}

    public bool ViewModelClosing
    { 
        get { return this._viewModelClosing; }
        set
        {
            if (value != this._viewModelClosing)
            {
                this._viewModelClosing = value;
                // odd to do it this way.
                // better bind a button event in view 
                // to the ViewModel.CloseView Command

                this.closeCommand.execute();
            }
        }
    }

    public ViewModel(ICommand closeCommand)
    {
        this.CloseView = closeCommand;
    }
}