开发者

TextBox in UserControl not rendering correctly

Suppose I have a UserControl Editor it has a TextBox. It also have a property Content. Here I just set the text content to a static value "Hey"

<UserControl x:Class="开发者_StackOverflow中文版WpfApplication1.Editor" ...>
    <TextBox Text="Hey" />
    <!--<TextBox Text="{Binding Content}" />-->
</UserControl>

Then I have a Window to display all this.

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

When I run it, I get

TextBox in UserControl not rendering correctly

Its not even a TextBox? And why do I get the content set in <local:Editor />. I tried Clean & Rebuild solution and I still get this wierd thing.


Issue


Simple enough. A UserControl is just a ContentControl actually, so it has a dependency property named Content. When you set this property, you set the whole content of your ContentControl. The Content property is the default one (have a look at default properties for WPF at MSDN).

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

Compare above and below codes:

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

In both cases, you define the Content property with different content...


Solution


To solve your issue, define a custom DependencyProperty in Editor named TextContent for instance, and do the following:

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

And:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜