【问题标题】:TextBox in UserControl not rendering correctlyUserControl 中的 TextBox 无法正确呈现
【发布时间】:2011-05-12 11:41:03
【问题描述】:

假设我有一个用户控件Editor,它有一个TextBox。它还有一个属性Content。这里我只是将文本内容设置为静态值“嘿”

<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>

当我运行它时,我得到了

它甚至不是一个文本框?以及为什么我会得到&lt;local:Editor /&gt; 中设置的内容。我尝试了 Clean & Rebuild 解决方案,但我仍然得到这个奇怪的东西。

【问题讨论】:

    标签: wpf binding user-controls textbox


    【解决方案1】:

    问题


    足够简单。 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 属性...


    解决方案


    要解决您的问题,请在 Editor 中定义一个自定义 DependencyProperty,例如命名为 TextContent,然后执行以下操作:

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

    还有:

    <local:Editor TextContent="Heya" />
    

    【讨论】:

    • 啊...终于,在挠了我这么久之后!
    猜你喜欢
    • 1970-01-01
    • 2020-02-24
    • 2014-03-19
    • 2015-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-19
    相关资源
    最近更新 更多