好吧,我有我的文件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>
Run Code Online (Sandbox Code Playgroud)
当我在编辑器中这似乎工作,但当我运行应用程序时,按钮的字体大小缩小到正常大小..
我的猜测是,当按钮的内容设置为字符串然后使用文本块样式时,按钮会创建一个TextBlock ..但我怎样才能覆盖它?
你是对的
我的猜测是,当按钮的内容设置为字符串然后使用文本块样式时,按钮会创建一个TextBlock
.看这篇文章.
解决方法是为System.String定义DataTemplate,我们可以在其中显式使用默认TextBlock来显示内容.您可以将DataTemplate放在定义TextBlock样式的同一个字典中,以便将此DataTemplate应用于受样式影响的任何ContentPresenter.
因此,最后将DataTemplate添加到Styles.xaml将解决问题
<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>
Run Code Online (Sandbox Code Playgroud)
这将保留TextBlock的Style,但是例如在Button中创建的TextBlock不会受其影响
我尝试了你的风格,效果很好。所以你的风格不是问题。我认为这是您在编写时合并风格的地方。您最好将 ResourceDictionary Styles.xaml 放在 MainWindow 文件中,而不是放在 Application.xaml 中。
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Styles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<StackPanel>
<TextBlock>TTT</TextBlock>
<Button>BBB</Button>
</StackPanel>
</Window>
Run Code Online (Sandbox Code Playgroud)
但是您的问题仍然不清楚,如果这不是解决方案,您能否通过发布这部分代码来进一步澄清您使用样式的方式?
| 归档时间: |
|
| 查看次数: |
14013 次 |
| 最近记录: |