WPF 更改样式按钮的字体大小失败?

标签 wpf styles

好吧,我的文件 Styles.xaml 已合并到 Application.xaml 中,因此它适用于所有事情。

这是我的风格

<Style TargetType="{x:Type Control}" x:Key="baseStyle">
    <Setter Property="FontFamily" Value="Verdana"/>
    <Setter Property="FontSize" Value="12"/>
</Style>

<Style TargetType="Button" BasedOn="{StaticResource baseStyle}">
    <Setter Property="Margin" Value="2,0,2,0"/>
    <Setter Property="Padding" Value="2"/>
    <Setter Property="FontSize" Value="50"/>
</Style>

<Style TargetType="TextBlock">
    <Setter Property="FontFamily" Value="Verdana"/>
    <Setter Property="FontSize" Value="12"/>
</Style>

当我在编辑器中时,这似乎有效,但是当我运行应用程序时,按钮的字体大小会缩小到正常大小。

我的猜测是,当按钮的内容设置为字符串时,它们会创建一个 TextBlock,然后使用 textblock 样式..但是我如何覆盖它?

最佳答案

你说得对

My guess is that the buttons create a TextBlock when their content is set to a string and then use the textblock style



.见 this邮政。

A workaround is to define a DataTemplate for System.String, where we can explicitly use a default TextBlock to display the content. You can place that DataTemplate in the same dictionary you define the TextBlock style so that this DataTemplate will be applied to whatever ContentPresenter effected by your style.



所以在 Styles.xaml 最后添加 DataTemplate 将解决问题
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:sys="clr-namespace:System;assembly=mscorlib">
    <Style TargetType="{x:Type Control}" x:Key="baseStyle">
        <Setter Property="FontFamily" Value="Verdana"/>
        <Setter Property="FontSize" Value="12"/>
    </Style>

    <Style TargetType="{x:Type Button}" BasedOn="{StaticResource baseStyle}">
        <Setter Property="Margin" Value="2,0,2,0"/>
        <Setter Property="Padding" Value="2"/>
        <Setter Property="Foreground" Value="Red" />
        <Setter Property="FontSize" Value="50"/>
    </Style>

    <Style TargetType="{x:Type TextBlock}">
        <Setter Property="FontFamily" Value="Verdana"/>
        <Setter Property="Foreground" Value="Green" />
        <Setter Property="FontSize" Value="24"/>
    </Style>

    <DataTemplate DataType="{x:Type sys:String}">
        <TextBlock Text="{Binding}">
            <TextBlock.Resources>
                <Style TargetType="{x:Type TextBlock}"/>
            </TextBlock.Resources>
        </TextBlock>
    </DataTemplate>
</ResourceDictionary>

这将保留您的 TextBlock 样式,但例如在 Button 中创建的 TextBlock 不会受到它的影响

关于WPF 更改样式按钮的字体大小失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4284513/

相关文章:

WPF 选项卡样式

c# - 组合框中的 WPF CultureInfo,DisplayName 作为 DisplayMemberPath 在更改 SelectedUICulture 时不起作用

c# - 在 UWP 中使用 DataTriggerBehavior 更改 ContentTemplate

css - 有没有办法使用 <article> css 来创建换行符?

css - 如何在相同大小的轮播中制作图像?

c# - ContextMenu 样式在不使用任何 Binding 的情况下产生奇怪的 Binding 错误

asp.net - CSS 与不同浏览器的兼容性

php - 彩色 var_dump() 和错误

android - 仅按钮左侧的边框

wpf - 如何将 System.Windows.Media.Color 对象序列化为 sRGB 字符串?