我有这个ResourceDictionary
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="MainMenuLabelStyle" TargetType="{x:Type TextBlock}">
<Style.Triggers>
<Trigger Property ="IsMouseOver" Value="True">
<Setter Property= "Foreground" Value="White"/>
<Setter Property= "FontSize" Value="18"/>
<Setter Property= "FontFamily" Value="Arial"/>
</Trigger>
</Style.Triggers>
</Style>
如果我想更改字体大小或颜色,该怎么办?此代码无效。
Application.Current.Resources("MainMenuLabelStyle") = 25
这是xaml
<TextBlock Text="Uscita" Grid.Row="1" Grid.Column="1" TextAlignment="Left" Margin="4" TextWrapping="Wrap" Style="{DynamicResource MainMenuLabelStyle}">
在WPF应用程序中首次使用样式之前,出于性能原因将其密封,无法再对其进行修改。您可以在MSDN上阅读它。
因此,如果要更改样式,则必须选择。第一个(最简单的方法)是声明所需的样式,并将它们放入您的中ResourceDictionary
。
第二种解决方案是考虑aSetter
是a DependencyObject
,因此可以绑定其依赖项属性。在这种情况下,您的样式将变为:
<Style x:Key="MainMenuLabelStyle" TargetType="{x:Type TextBlock}">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground" Value="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Tag.Foreground, TargetNullValue=Red, FallbackValue=Red}" />
<Setter Property="FontSize" Value="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Tag.FontSize, TargetNullValue=18, FallbackValue=18}" />
<Setter Property="FontFamily" Value="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Tag.FontFamily, TargetNullValue=Arial, FallbackValue=Arial}" />
</Trigger>
</Style.Triggers>
</Style>
现在,您只需设置Tag
每个TextBlock
控件的属性即可更改样式:
<StackPanel>
<TextBlock Text="Uscita" TextAlignment="Left" Margin="4" TextWrapping="Wrap" Style="{DynamicResource MainMenuLabelStyle}" />
<TextBlock Text="Uscita" TextAlignment="Left" Margin="4" TextWrapping="Wrap" Style="{DynamicResource MainMenuLabelStyle}">
<TextBlock.Tag>
<local:StyleConfig FontSize="50" FontFamily="Tahoma" Foreground="Orange" />
</TextBlock.Tag>
</TextBlock>
</StackPanel>
如您所见,第一个TextBlock
将使用声明的样式。另一方面,第二个TextBlock
将使用原始样式的修改版本。
当然,为了使此选项正常工作,您必须创建一个类(StyleConfig
在我的示例中),该类可能是这样的:
public class StyleConfig
{
public string Foreground { get; set; }
public string FontSize { get; set; }
public string FontFamily { get; set; }
}
希望对您有所帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句