WPF:决定在用户​​控件中的何处显示 contentPresenter

WPF: decide where to show the contentPresenter in your User control

我有一个非常简单的 UserControl,带有一些边框和一些对 mouseOver、按下和一些不错的东西有反应的装饰。

我想允许人们从外部设置文本的内容,但是当我设置内容时,生成的内容展示器覆盖了我的整个 WPF 结构。

这是我目前尝试的方法:

<UserControl tags tags tags>
    <!-- This is the only way I found to style the textblock that WPF -->
    <!-- generates to encapsulate the content string -->
    <UserControl.Template>
        <ControlTemplate TargetType="UserControl">
            <TextBlock Background="Green"
                       HorizontalAligment="Center"
                       VerticalAlignment="Center"
                       Text = "{TemplateBinding Content}"/>
        </ControlTemplate>
    </UserControl.Template>

    <!-- Here my borders and fancy things. I want to add animations -->
    <!-- and react to mouseOver and Pressed like a button -->

    <Border x:Name="SuperNiceBorder" tag tag tag>
        <HERE I WANT THE CONTENTPRESENTER>
    </Border>

</UserControl>

有没有办法告诉 WPF 我想要用户在内容中设置的文本???

将所有动画和触发器移到 ControlTemplate 中。

用 ContentPresenter 替换您的 TextBlock:

<UserControl x:Class="MySolution.MyControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <UserControl.Template>
        <ControlTemplate TargetType="UserControl">
            <Border x:Name="MyBorder" Background="Green">
            <ContentPresenter
                       HorizontalAlignment="Center"
                       VerticalAlignment="Center"
                       Content = "{TemplateBinding Content}"/></Border>

            <ControlTemplate.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter TargetName="MyBorder" Property="Background" Value="Red"/>
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </UserControl.Template>

</UserControl>

并且您可以像这些示例一样使用 UserControl:

1:

    <local:MyControl Content="Test Testing tester"/>

2:

    <local:MyControl>
        <TextBlock Text="Another test from a TextBlock"/>
    </wpfAllPurposesTest:MyControl>