为什么按钮字体在窗口上添加文本元素时没有效果


<Window.Resources>
    <Style TargetType="{x:Type TextElement}">
        <Setter Property="FontSize" Value="50"/>
    </Style>
</Window.Resources>
<Grid>
    <StackPanel Orientation="Vertical" Grid.Column="0" >
        <Button Click="ButtonBase_OnClick" x:Name="qq">xxx</Button>
        <Button>xxx</Button>
        <Button>xxx</Button>
    </StackPanel>
</Grid>

像上面的代码

我知道,按钮的字体大小是文本元素的DP,但是为什么此代码无效?

 <Window.Resources>
    <Style TargetType="{x:Type Button}">
        <Setter Property="FontSize" Value="50"/>
    </Style>
</Window.Resources>

如果我将文本元素更改为按钮,一切正常,为什么?

Button不同,TextElement不是Control。它不会从System.Windows.Control类继承,并且没有ControlTemplate,因此,隐含样式不会应用。请参阅以下链接以获取有关此的更多信息。

https://blogs.msdn.microsoft.com/wpfsdk/2009/08/27/implitic-styles-templates-controls-controls-and-frameworkelements/application.resources vs window.resources?

中的隐性样式

如果要定义全局文本样式,则可以向App.xaml添加隐式TextBlock样式:

<Application x:Class="WpfApp1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp2"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <Style TargetType="{x:Type TextBlock}">
            <Setter Property="FontSize" Value="50"/>
        </Style>
    </Application.Resources>
</Application>

您遇到的问题是属性继承(来自Button控件(的优先级低于样式设置器(来自Application中的Style(。

请查看MSDN上的依赖项属性值优先页,以列出所有先例的排序列表。

要设置应在MainWindow上设置FontSize的全局文本大小。这样,您仍然可以使用继承和样式覆盖全局文本大小。

最新更新