我试图让自己从Control派生的ContentControl完全理解黑暗的wpf树概念。目前,我刚刚实现了ContentControl的逻辑部分(Content)。WPF:绑定找不到源
我后面的代码:
[ContentProperty("Content")]
public class MyContentControl : Control
{
public MyContentControl()
{
}
public Object Content
{
get { return (Object)GetValue(ContentProperty); }
set { SetValue(ContentProperty, value); }
}
public static readonly DependencyProperty ContentProperty =
DependencyProperty.Register("Content", typeof(Object), typeof(MyContentControl), new UIPropertyMetadata());
}
XAML:
<StackPanel x:Name="stackPanel">
<TextBlock Visibility="Collapsed" x:Name="textBlock" Text="Hello World"/>
<ContentControl>
<TextBlock Background="LightBlue" Text="{Binding Text, ElementName=textBlock}"/>
</ContentControl>
<local:MyContentControl>
<TextBlock Text="{Binding Text, ElementName=textBlock}"/>
</local:MyContentControl>
</StackPanel>
我得到了以下绑定错误:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=textBlock'. BindingExpression:Path=Text; DataItem=null; target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')
它像内的TextBlock中上不去逻辑树并找到它应该绑定的原始文本块。我无法将myContentControl设置为Content对象的父级。
任何idee?
感谢您的时间。
乔纳斯
谢谢您的回答。我需要再考虑一下,但你的链接非常有帮助。我不想更改xaml,但我想知道在哪种方式下,我应该修改MyContentControl后面的代码,使其可以具有与ContentControl完全相同的行为。 – Jonas