带有 MVVM 和依赖属性的 WPF 用户控制地狱 [英] WPF User Control hell with MVVM and Dependency Properties
问题描述
这就是我想要做的:
- 我正在编写一个
UserControl
,我希望其他开发者使用它. 我希望最终用户能够通过依赖属性使用我的控件.
- I'm writing a
UserControl
that I want to be consumed by other developers. I want end users to be able to use my control using Dependency Properties.
<lib:ControlView ControlsText={Binding Path=UsersOwnViewModelText} />
我使用的是 MVVM 模式.
I'm using the MVVM pattern.
我正在使用
<DataTemplate DataType="{x:Type local:ControlViewModel}">
<local:ControlView />
</DataTemplate>
所以我有两个问题:
我是否正确地认为,如果在 XAML 中使用 UserControl,那么当控件的
Loaded
事件触发时,UserControl 必须将 ViewModel 设置为其DataContext
而不是使用
方法?
Am I right in thinking that if a UserControl is being consumed in XAML then the UserControl must set the ViewModel as its
DataContext
when the control'sLoaded
event fires instead of using the<DataTemplate>
method?
如何允许用户将数据绑定到我的控件的依赖项属性,同时仍然将数据绑定到我的 ViewModel?
How do I allow users to data bind to my control's dependency properties while still being data bound to my ViewModel?
推荐答案
首先,我不认为 MVVM 是一个好的选择,如果您正在开发一个将被其他人使用的 UserControl.无外观控件才是您真正应该开发的控件.Jeremiah Morrill 有一个 博客文章 关于这个主题.
First off, I don't think MVVM is a good choice if you are developing a UserControl that will be consumed by others. A lookless control is what you really should be developing. Jeremiah Morrill has a blog post about this subject.
话虽如此,如果您有默认的公共构造函数,则可以使用 XAML 设置数据上下文.
With that said, you can set the datacontext with XAML if you have a default public constructor.
在 ControlView.xaml 中放置:
Inside ControlView.xaml put:
<UserControl.DataContext>
<local:ControlViewModel />
</UserControl.DataContext>
这篇关于带有 MVVM 和依赖属性的 WPF 用户控制地狱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!