【发布时间】:2011-11-30 14:07:34
【问题描述】:
我尝试制作自己的从 Control 派生的 ContentControl,以完全理解深色 wpf 树的概念。目前,我只是实现了 ContentControl 的逻辑部分(内容)。
我的代码:
[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 错误:4:找不到引用“ElementName=textBlock”的绑定源。绑定表达式:路径=文本;数据项=空;目标元素是'TextBlock'(名称='');目标属性是“文本”(类型“字符串”)
这就像内部的 TextBlock 无法在逻辑树中找到它应该绑定的原始文本块。我无法将 myContentControl 设置为 Content 对象的父级。
有什么想法吗?
感谢您的宝贵时间。
乔纳斯
【问题讨论】:
标签: wpf binding custom-controls