C# WPF控制&x27;s嵌套属性';s数据绑定
我正在尝试开发一些嵌套属性的用户控件,这些属性允许使用数据绑定进行设置。例如,我有这样的东西:C# WPF控制&x27;s嵌套属性';s数据绑定,c#,wpf,xaml,data-binding,C#,Wpf,Xaml,Data Binding,我正在尝试开发一些嵌套属性的用户控件,这些属性允许使用数据绑定进行设置。例如,我有这样的东西: // Top level control public class MyControl : Control { public string TopLevelTestProperty { get { return (string)GetValue(TopLevelTestPropertyProperty); } set { SetValue(TopLeve
// 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:
它适用于属性TopLevelTestProperty,但不适用于NestedTestProperty。
嵌套绑定似乎不起作用。有人能帮我吗?有没有办法使这种约束力?
我认为这是因为我的嵌套对象没有对顶级对象的任何引用,因此无法使用MyControl的DataContext来解析它。对,嵌套控件不会从MyControl继承DataContext。
Tyr明确规定:
绑定错误说明了什么?它说:“找不到目标元素的治理FrameworkElement或FrameworkContentElement。BindingExpression:Path=Value;DataItem=null;目标元素是‘MyNestedType’;目标属性是‘NestedTestProperty’(类型‘String’)”。您缺少一个……看起来是这样的。。。我想知道是否可以将它添加到我的类型中…所以唯一的方法是从FrameworkElement或FrameworkContentElement继承mynestedtype(因为mynestedtype中没有DataContext属性),不是吗?但对于DependencyObject有什么方法可以做到这一点吗?FrameworkElement提供了许多我不想要的属性。
<local:mycontrol x:name="myControl" topleveltestproperty="{Binding Value}" >
<local:mycontrol.nestedobject>
<local:mynestedtype x:name="myNestedControl" nestedtestproperty="{Binding Value}" />
</local:mycontrol.nestedobject>
</local:mycontrol>