WPF控件的嵌套属性的数据绑定 [英] WPF Control's Nested property's data binding
问题描述
我正在尝试开发具有一些嵌套属性的用户控件,这些控件允许使用数据绑定进行设置.例如,我有这样的东西:
I'm trying to develop user control with some nested properties that allows to use databinding to set it. For example, I have something like this:
// Top level control
public class MyControl : Control
{
public string TopLevelTestProperty
{
get { return (string)GetValue(TopLevelTestPropertyProperty); }
set { SetValue(TopLevelTestPropertyProperty, value); }
}
public static readonly DependencyProperty TopLevelTestPropertyProperty =
DependencyProperty.Register("TopLevelTestProperty", typeof(string), typeof
(MyControl), new UIPropertyMetadata(""));
// This property contains nested object
public MyNestedType NestedObject
{
get { return (MyNestedType)GetValue(NestedObjectProperty); }
set { SetValue(NestedObjectProperty, value); }
}
public static readonly DependencyProperty NestedObjectProperty =
DependencyProperty.Register("NestedObject", typeof(MyNestedType), typeof
(MyControl), new UIPropertyMetadata(null));
}
// Nested object's type
public class MyNestedType : DependencyObject
{
public string NestedTestProperty
{
get { return (string)GetValue(NestedTestPropertyProperty); }
set { SetValue(NestedTestPropertyProperty, value); }
}
public static readonly DependencyProperty NestedTestPropertyProperty =
DependencyProperty.Register("NestedTestProperty", typeof(string), typeof
(MyNestedType), new UIPropertyMetadata(""));
}
// Sample data context
public class TestDataContext
{
public string Value
{
get
{
return "TEST VALUE!!!";
}
}
}
...
this.DataContext = new TestDataContext();
...
XAML:
<local:mycontrol x:name="myControl" topleveltestproperty="{Binding Value}" >
<local:mycontrol.nestedobject>
<local:mynestedtype x:name="myNestedControl" nestedtestproperty="{Binding Value}" />
</local:mycontrol.nestedobject>
</local:mycontrol>
它对于属性TopLevelTestProperty效果很好,但不适用于NestedTestProperty.似乎嵌套绑定不起作用.有人可以帮我吗?有什么办法可以进行这种绑定吗?我认为发生这种情况是因为我的嵌套对象没有对顶级对象的任何引用,因此无法使用MyControl的DataContext对其进行解析.
It works well for property TopLevelTestProperty, but it doesn't work for NestedTestProperty. It seems that nested bindings do not work. Can anybody help me please? Is there any way to make such binding? I think that it happens because of my nested object has no any reference to the top level object, so it cannot be resolved using MyControl's DataContext.
推荐答案
HB 正确,嵌套控件不会继承DataContext来自 mycontrol
.明确设置它:
H.B. right, nested control does not inherit DataContext from mycontrol
.
Tyr out setting it explicitly:
<local:mycontrol x:name="myControl"
topleveltestproperty="{Binding Value}" >
<local:mycontrol.nestedobject>
<local:mynestedtype x:name="myNestedControl"
DataContext="{Binding ElementName=myControl,
Path=DataContext}"
nestedtestproperty="{Binding Value}" />
</local:mycontrol.nestedobject>
</local:mycontrol>
这篇关于WPF控件的嵌套属性的数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!