2010-11-19 141 views
0

假设我有一个UserControl Editor它有一个TextBox。它也有一个属性Content。在这里,我只是设置文本内容的静态值“嘿”UserControl中的TextBox无法正确呈现

<UserControl x:Class="WpfApplication1.Editor" ...> 
    <TextBox Text="Hey" /> 
    <!--<TextBox Text="{Binding Content}" />--> 
</UserControl> 

然后,我有一个窗口来显示这一切。

<Window x:Class="WpfApplication1.Window1" ...> 
    <StackPanel> 
     <local:Editor Content="Heya" /> 
    </StackPanel> 
</Window> 

当我运行它,我得到

alt text

它甚至不是一个TextBox?为什么我会收到<local:Editor />中设置的内容。我试过清洁&重建解决方案,我仍然得到这个奇怪的事情。

回答

2

问题


够简单。 A UserControl实际上只是一个ContentControl,所以它有一个名为Content的依赖项属性。当您设置此属性时,您将设置您的ContentControl的全部内容。 Content属性是默认属性(查看MSDN的WPF默认属性)。

<UserControl x:Class="WpfApplication1.Editor" ...> 

    <!-- Here, you set the Content property (because it is 
    the default one) of the UserControl as a TextBox with 
    the text "Hey". --> 

    <TextBox Text="Hey" /> 
</UserControl> 

比较上面和下面的代码:

<!-- Here, the Content property is explicitly set. --> 
<local:Editor Content="Heya" /> 

在这两种情况下,您可以定义不同的内容Content属性...


解决方案


为了解决您的问题,定义一个定制DependencyPropertyEditor命名TextContent例如,然后执行以下操作:

<UserControl x:Class="WpfApplication1.Editor" ...> 
    <TextBox Text="{Binding TextContent, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" /> 
</UserControl> 

和:

<local:Editor TextContent="Heya" /> 
+0

啊......刮伤的最后,经过这么长时间我的头! – 2010-11-19 09:56:41