当UserControl具有DataContext时,UserControl的DependencyProperty为null
我已经向我的View添加了DependencyProperty,绑定到DependencyProperty工作,但前提是我还没有设置DataContext。
GenericView.xaml
GenericView.xaml.cs
public partial class GenericView : UserControl { // The DependencyProperty for VMFactory. public static readonly DependencyProperty VMFactoryProperty = DependencyProperty.Register("VMFactory", typeof(VMFactoryViewModel), typeof(GenericView)); public VMFactoryViewModel VMFactory { get { return (VMFactoryViewModel)GetValue(VMFactoryProperty); } set { SetValue(VMFactoryProperty, value); } } public GenericView() { InitializeComponent(); } }
在这里,我创建了两个视图来说明手头的问题。 第一个视图中的VMFactory绑定将失败,因为我已设置DataContext。 第二种观点会成功,这种行为的原因是什么?
MainPage.xaml中
这是一个相当常见的绑定“陷阱”……
要访问VMFactory
,您需要使用…将UserControl
绑定到自身。
DataContext="{Binding RelativeSource={RelativeSource Self}}"
然后,您不会将GenericView
项上的DataContext
绑定到其他任何位置。
但是,如果您打算将其他值绑定到UserControl
外部的VMFactory
(即
),则应使用具有FindAncestor
模式的RelativeSource
作为UserControl
类型。
正如@toadflakz所说,这是WPF中一个非常常见的问题,而且当我学习WPF时,我花了一些时间来解决这个问题。 幸运的是,解决方案很简单。 假设我们有一个UserControl
,其对象设置为其DataContext
,另一个设置为在UserControl
声明的DependencyProperty
的值…您的情况。
在 UserControl
XAML中,您可以像往常一样将数据绑定到作为DataContext
设置的对象的属性:
如果要将数据绑定到对象集中的对象设置为DependencyProperty
的值,则只需使用RelativeSource Binding
:
请注意,只要设置了DataContext
和DependencyProperty
属性,这两个Binding
都可以在同一个UserControl
一起使用。
我有一个有效的解决方案,似乎控件的属性是相对于控件的DataContext绑定的?
我当然知道控件中的项目将相对于DataContext绑定,但我显然以前从未使用过这种方式的控件,并且不明白控件的属性也会inheritanceset DataContext的范围。 基本上我的视图中的所有内容都是正确的,但是对我的DependencyProperty的绑定失败了。
GenericView.xaml
MainPage.xaml中