问题描述
我试图使用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:
-
DependencyObjects
未标记为可序列化。 -
DependencyObject
类会覆盖并密封Equals()
和
GetHashCode()
方法。 -
A
DependencyObject
具有线程相似性-
只能在创建它的线程上访问。
DependencyObjects
are not marked as serializable.- The
DependencyObject
class overrides and seals both theEquals()
andGetHashCode()
methods. 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!