Should ViewModel inherit DependencyObject in WPF?

冷暖自知 提交于 2019-12-23 20:00:24

问题


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?


回答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.



来源:https://stackoverflow.com/questions/28688179/should-viewmodel-inherit-dependencyobject-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!