【问题标题】:Is it possible execute a method in the view when a property changes in the view model, with MVVM pattern?当视图模型中的属性发生更改时,是否可以使用 MVVM 模式在视图中执行方法?
【发布时间】:2013-05-05 07:06:32
【问题描述】:

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

所以我是这样想的:

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

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

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

有可能吗?

【问题讨论】:

标签: c# wpf mvvm


【解决方案1】:

阿尔瓦罗·加西亚

最简单也是 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;
    }
}

【讨论】:

    猜你喜欢
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 2017-10-24
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多