ViewModel是否应该继承WPF中的DependencyObject? [英] Should ViewModel inherit DependencyObject in WPF?

查看:120
本文介绍了ViewModel是否应该继承WPF中的DependencyObject?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用MVVM在WPF中创建一个简单的 UserControl 。现在,我需要为 UserControl 创建一个依赖项属性,因此我尝试在 UserControlViewModel 中创建依赖项属性(我

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

为了在 UserControlViewModel 中创建依赖项属性,需要从 DependencyObject 继承。在 UserControlViewModel 中继承 DependencyObject 是一个好习惯吗?也就是说,遵循MVVM来设计 UserControl 的好方法吗?

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?

推荐答案

如果您创建的自定义控件的属性要可绑定(例如以下代码),则不能使用 INotifyPropertyChanged ,并且您必须使用 DependencyObject

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}"  />

但是当使用 DependencyObjects 时,请注意:

But when using DependencyObjects you should keep in mind that:


  1. DependencyObjects 未标记为可序列化。

  2. DependencyObject 类会覆盖并密封 Equals()
    GetHashCode()方法。

  3. A DependencyObject 具有线程相似性-
    只能在创建它的线程上访问。

  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.


  • 查看讨论在View-Model中实现INPC和DP的良好MVVM示例,请参见此文章

有关INPC与DP辩论的更多信息,请阅读此博客

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

这篇关于ViewModel是否应该继承WPF中的DependencyObject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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