被覆盖的 Style of TextBlock 的奇怪行为

本文关键字:of 覆盖 Style TextBlock | 更新日期: 2023-09-27 18:36:36

几天前,我遇到了按钮内部文本的奇怪行为(我想与其他ContentControls相同的行为)。让我解释一下情况。我在 App.xaml 中有一个用于 TextBlock 的样式定义:

<Application.Resources>
    <Style TargetType="{x:Type TextBlock}">
        <Setter Property="Margin" Value="10"/>
    </Style>
</Application.Resources>

在 MainWindow.xaml 中,我具有相同的样式定义,该定义应覆盖 App.xaml 中定义的样式。我在窗口中也有 3 个按钮。在第一个按钮中显式定义了按钮内容中的 TextBlock 控件。对于第二个按钮,我将字符串设置为代码隐藏中的内容。对于第三个按钮,我将一个整数值设置为代码隐藏中的内容。以下是 MainWindow.xaml 的代码:

<StackPanel>
    <StackPanel.Resources>
        <Style TargetType="{x:Type TextBlock}">
            <Setter Property="Margin" Value="0"/>
        </Style>
    </StackPanel.Resources>
    <Button Name="Button1">
        <Button.Content>
            <TextBlock Text="Button with text block"/>
        </Button.Content>
    </Button>
    <Button Name="Button2" />
    <Button Name="Button3" />
</StackPanel>

和 MainWindow.xaml.cs:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    Button2.Content = "Button with string";
    Button3.Content = 16;
}

现在我们看到了什么?正如预期的那样,第一个和第三个按钮中的文本的边距为 0px,但第二个按钮中的文本的边距为 10px!问题是:为什么第二个按钮有 10px 边距以及如何为第二个按钮设置零边距(无法从 App.xaml 中删除样式)?

谢谢!

被覆盖的 Style of TextBlock 的奇怪行为

当我改变时

Button2.Content = "Button with string"; 

Button2.Content = "Button with _string"; 

按钮的边距从 10 更改为 0。

这是 WPF 中的一个错误;Microsoft Connect 上已经报告了它。

我不是100%确定,但我认为您看到的行为是由相同的根本原因引起的。

顺便说一下:正确的行为是按钮 2 和 3 的 Margin=10;这是因为资源查找是沿着逻辑树而不是沿着可视化树执行的。按钮 2 和 3 中的文本块不在堆栈面板的逻辑树内。

我不能给你一个明确的答案,但我注意到设置字符串和整数之间的区别会导致应用不同的样式。

由于将内容设置为需要转换的值会导致应用正确的样式,因此我尝试了以下方法:

private void WindowLoaded(object sender, RoutedEventArgs e)
{
    Button2.Content = new TextHolder("Button with string");
    Button3.Content = 16;
}
public class TextHolder
{
    private readonly string _text;
    public TextHolder(string text)
    {
        _text = text;
    }
    public override string ToString()
    {
        return _text;
    }
}

保证金现在为 0。 我有兴趣确切地了解正在发生的事情。