Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should ViewModel inherit DependencyObject in WPF?

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 code-behind).

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?

like image 259
Raja Avatar asked Dec 24 '22 22:12

Raja


1 Answers

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.

like image 155
Bahman_Aries Avatar answered Dec 27 '22 20:12

Bahman_Aries