WPF:决定在User控件中显示contentPresenter的位置

问题描述 投票:1回答:1

我有一个非常简单的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我想要用户在内容中设置的文本就在那里???

wpf user-controls contentpresenter
1个回答
2
投票

在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>
© www.soinside.com 2019 - 2024. All rights reserved.