如何在MVVM中编写ViewModelBase [英] How to write a ViewModelBase in MVVM

查看:687
本文介绍了如何在MVVM中编写ViewModelBase的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在WPF编程环境中还很陌生.我正在尝试使用MVVM设计模式编写程序.

I'm pretty new in WPF programming environment. I'm trying to write a program out using MVVM design pattern.

我已经做过一些研究,并阅读了一些与之相关的文章,而且很多时候我遇到了一个叫做

I've did some studies and read up some articles related to it and many of a time I came across this thing called

ViewModelBase

ViewModelBase

我知道它是什么..但是我是否可以具体知道我应该从哪里开始,以便能够写出自己的ViewModelBase?就像...真正了解正在发生的事情,而不必太复杂.谢谢:)

I know what it is.. But may I know specifically where should I begin with to be able to write out my own ViewModelBase? Like... Really understanding what's happening without getting too complicated. Thank you :)

推荐答案

如果您不知道内部发生了什么,那么使用MVVM框架就一文不值.

It's worth nothing to use MVVM frameworks if you don't know what's going on inside.

因此,让我们一步一步地构建自己的ViewModelBase类.

So let's go step by step and build your own ViewModelBase class.

  1. ViewModelBase是所有视图模型的通用类.让我们将所有常见的逻辑移到此类.

  1. ViewModelBase is class common for all your viewmodels. Let's move all common logic to this class.

您的ViewModels应该实现INotifyPropertyChanged(您知道为什么吗?)

Your ViewModels should implement INotifyPropertyChanged (do you understand why?)

public abstract class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

[CallerMemberName]属性不是必需的,但它允许您编写: OnPropertyChanged();而不是OnPropertyChanged("SomeProperty");,因此您将避免在代码中使用字符串常量.示例:

the [CallerMemberName] attribute is not required, but it will allow you to write: OnPropertyChanged(); instead of OnPropertyChanged("SomeProperty");, so you will avoid string constant in your code. Example:

public string FirstName
{
    set
    {
        _firtName = value;
        OnPropertyChanged(); //instead of OnPropertyChanged("FirstName") or OnPropertyChanged(nameof(FirstName))
    }
    get{ return _firstName;}
}

请注意,由于我们在C#6中具有nameof运算符,因此不再建议使用OnPropertyChanged(() => SomeProperty).

Please note, that OnPropertyChanged(() => SomeProperty) is no more recommended, since we have nameof operator in C# 6.

通常的做法是实现调用PropertyChanged的属性,如下所示:

It's common practice to implement properties that calls PropertyChanged like this:

public string FirstName
{
    get { return _firstName; }
    set { SetProperty(ref _firstName, value); }
}

让我们在您的viewmodelbase中定义SetProperty:

Let's define SetProperty in your viewmodelbase:

protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = "")
{
    if (EqualityComparer<T>.Default.Equals(storage, value))
        return false;
    storage = value;
    this.OnPropertyChanged(propertyName);
    return true;
}

当属性的值更改并返回true时,它仅触发PropertyChanged事件.当值未更改并返回false时,它不会触发事件.基本思想是,SetProperty方法是虚拟的,您可以将其扩展到更具体的类中,例如,以触发验证或通过调用PropertyChanging事件.

It simply fires PropertyChanged event when value of the property changes and returns true. It does not fire the event when the value has not changed and returns false. The basic idea is, that SetProperty method is virtual and you can extend it in more concrete class, e.g to trigger validation, or by calling PropertyChanging event.

这很漂亮.这是您的ViewModelBase在此阶段应包含的所有内容.其余的取决于您的项目.例如,您的应用程序使用页面基础导航,并且您编写了自己的NavigationService来处理ViewModel的导航.因此,您可以将NavigationService属性添加到您的ViewModelBase类中,以便您可以从所有视图模型中访问它.

This is pretty it. This is all your ViewModelBase should contain at this stage. The rest depends on your project. For example your app uses page base navigation and you have written your own NavigationService for handling navigation from ViewModel. So you can add NavigationService property to your ViewModelBase class, so you will have access to it from all your viewmodels, if you want.

为了获得更高的可重用性并保持SRP,我有一个名为 BindableBase 的类,该类几乎是INotifyPropertyChanged的实现,就像我们在这里所做的那样.我在每个WPF/UWP/Silverligt/WindowsPhone解决方案中都重复使用该类,因为它是通用的.

In order to gain more reusability and keep SRP, I have class called BindableBase which is pretty much the implementation of INotifyPropertyChanged as we have done here. I reuse this class in every WPF/UWP/Silverligt/WindowsPhone solution because it's universal.

然后在每个项目中,我创建一个从BindableBase派生的自定义ViewModelBase类:

Then in each project I create custom ViewModelBase class derived from BindableBase:

public abstract ViewModelBase : BindableBase
{
    //project specific logic for all viewmodels. 
    //E.g in this project I want to use EventAggregator heavily:
    public virtual IEventAggregator () => ServiceLocator.GetInstance<IEventAggregator>()   
}

如果我有应用程序,该应用程序使用基于页面的导航,那么我还要为页面视图模型指定基类.

if I have app, that uses page based navigation I also specify base class for page viewmodels.

public abstract PageViewModelBase : ViewModelBase
{
    //for example all my pages has title:
    public string Title {get; private set;}
}

我可以为对话框设置另一个类:

I could have another class for dialogs:

public abstract DialogViewModelBase : ViewModelBase
{
    private bool? _dialogResult;

    public event EventHandler Closing;

    public string Title {get; private set;}
    public ObservableCollection<DialogButton> DialogButtons { get; }

    public bool? DialogResult
    {
        get { return _dialogResult; }
        set { SetProperty(ref _dialogResult, value); }
    }

    public void Close()
    {
        Closing?.Invoke(this, EventArgs.Empty);
    }
}

这篇关于如何在MVVM中编写ViewModelBase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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