简体   繁体   English

ViewModel 应该继承 WPF 中的 DependencyObject 吗?

[英]Should ViewModel inherit DependencyObject in WPF?

I tried to create a simple UserControl in WPF using MVVM.我尝试使用 MVVM 在 WPF 中创建一个简单的UserControl 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).现在我需要为UserControl创建一个依赖属性,所以我尝试在UserControlViewModel创建依赖属性(我不想在代码隐藏中)。

In order to create a dependency property in UserControlViewModel I need to inherit from DependencyObject .为了在UserControlViewModel创建依赖属性,我需要从DependencyObject继承。 Is it a good practice to inherit DependencyObject in UserControlViewModel ?UserControlViewModel继承DependencyObject是一个好习惯吗? That is, is it a good way to follow MVVM for designing a UserControl ?也就是说,这是遵循 MVVM 设计UserControl的好方法吗?

If you have created a custom control with properties that you want them to be bindable (eg the following code), you cannot use INotifyPropertyChanged and you must use a DependencyObject .如果您创建的自定义控件具有您希望它们可绑定的属性(例如以下代码),则不能使用INotifyPropertyChanged并且必须使用DependencyObject

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

But when using DependencyObjects you should keep in mind that:但是在使用DependencyObjects您应该记住:

  1. DependencyObjects are not marked as serializable. DependencyObjects未标记为可序列化。
  2. The DependencyObject class overrides and seals both the Equals() and GetHashCode() methods. DependencyObject类覆盖并密封了Equals()GetHashCode()方法。
  3. A DependencyObject has thread affinity - it can only be accessed on the thread on which it was created. DependencyObject具有线程关联性 - 它只能在创建它的线程上访问。

    • To see a good MVVM example that discusses implementation of INPC and DP in View-Model see this article .要查看一个很好的 MVVM 示例,该示例讨论了 View-Model 中 INPC 和 DP 的实现,请参阅本文

    • For more on the INPC vs DP debate, read this blog .有关 INPC 与 DP 辩论的更多信息,请阅读此博客

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM