问题
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:
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.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