Should ViewModel inherit DependencyObject in WPF?

2019-07-21 03:03发布

问题:

I tried to create a simple UserControl in WPF using MVVM. Now I need to create a dependency property for the UserControl, so I tried to create the dependency property in UserControlViewModel (I don't want to be in codebehind).

In order to create a dependency property in UserControlViewModel I need to inherit from DependencyObject. Is it a good practice to inherit DependencyObject in UserControlViewModel? That is, is it a good way to follow MVVM for designing a UserControl?

回答1:

If you have created a custom control with properties that you want them to be bindable (e.g. the following code), you cannot use INotifyPropertyChanged and you must use a DependencyObject.

<MyUserControl MyDependencyProperty="{Binding PropertyPath}"  />

But when using DependencyObjects you should keep in mind that:

  1. DependencyObjects are not marked as serializable.
  2. The DependencyObject class overrides and seals both the Equals() and GetHashCode() methods.
  3. A DependencyObject has thread affinity - it can only be accessed on the thread on which it was created.

    • To see a good MVVM example that discusses implementation of INPC and DP in View-Model see this article.

    • For more on the INPC vs DP debate, read this blog.