.net - 在 Label 的内容中明确使用 TextBlock 会使 ContentPresenter 行为异常

标签 .net wpf templates xaml label

我有一个带有双 ContentPresenter 的自定义 ControlTemplate。该模板应用于 Label。当我将“Random octopus”(只是文本)设置为标签的内容时,它完全按预期工作。当我将“Random octopus”设置为 Content 时,它不起作用(只有一个 ContentPresenter 在视觉上表示)。我使用以下代码重现该行为:

<Window x:Class="WeirdTextBlock.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Window.Resources>
        <Style TargetType="Label">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Label">
                        <Border BorderBrush="Red" BorderThickness="1" Padding="2">
                            <Grid>
                                <ContentPresenter />
                                <ContentPresenter Margin="2,2,0,0" />
                            </Grid>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>

    <Grid Margin="20" HorizontalAlignment="Left">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="20" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
    
        <Label Grid.Row="0">
            Random octopus
        </Label>
    
        <Label Grid.Row="2">
            <TextBlock>Random octopus</TextBlock>
        </Label>
    </Grid>
</Window>

在这里你可以看到它的样子:

我以为when you enter just text into Content property, it gets wrapped by TextBlock ,那么为什么第二个标签的视觉表现与第一个不同呢?以及如何使第二个标签的行为正确(使其看起来像第一个标签,但只能通过修改模板)?谢谢!

最佳答案

这里的根本问题是您试图同时在两个不同的位置放置视觉对象(TextBlock)。一个视觉对象只能有一个父级,因此其中一个内容呈现器“获胜”,而另一个将没有任何内容。

如果您只想拥有 TextBlock 的可视副本,那么请使用 VisualBrush .

关于.net - 在 Label 的内容中明确使用 TextBlock 会使 ContentPresenter 行为异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5134381/

相关文章:

c# - Visual Studio 2012 中的 MVVM Light 不显示项目模板

c++ - SFINAE 以返回类型工作,但不作为模板参数

c++ - 是否可以用 C++ 编写不纯的模板?

javascript - 有什么方法可以将自定义元素的模板标记和样式保留在 JavaScript 字符串之外?

c# - 如何确定通过实例化 COM coclass 启动的进程的 PID?

.net - 如何将get-item cmdlet的输出作为字符串输出到变量

c# - 在不知道 T 的情况下将泛型类型指定为参数参数

c# - 有没有办法在 C# 应用程序中保持电子邮件 session ?

c# - 如何防止将 Item 添加到 DataGrid?

wpf - 在桌面应用程序(非 UWP)中使用 XAML DeferLoadStrategy ="Lazy"