WPF 资源覆盖 [英] WPF Resource overriding
问题描述
我有一个关于 xaml wpf 样式的问题.
I have a question regarding styles in xaml wpf.
我有一个适用于所有对象的默认样式.但是对于其中一些我想设置第二个样式来覆盖一些属性.
I have a Default style which should apply for all Objects. But for some of them I want to set a second style overriding a few attributes.
现在,如果我给我的第二个样式一个 x:key="style2" 并将其设置为样式,则不会应用我的第一个默认样式,但会应用默认 WPF 样式.我不能/不想在我的第一个默认样式中更改任何内容
Now if I give my second style a x:key="style2" and set this as style, my first Default style is not applied, but the Default WPF style is. I can not/want not Change anything at my first Default style
我该如何解决这种行为?
How can I fix this behaivor?
推荐答案
为确保仍然应用您的默认样式,您添加
To ensure that your default style is still applied, you add
BasedOn={StaticResource ResourceKey={x:Type ControlType}}
其中 ControlType
是应用默认样式的对象类型.
Where ControlType
is the type of object the default style was applied to.
这是一个例子:
<Window x:Class="StyleOverrides.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="FontFamily" Value="Comic Sans MS" />
</Style>
<Style x:Key="Specialization"
TargetType="{x:Type TextBlock}"
BasedOn="{StaticResource ResourceKey={x:Type TextBlock}}"
>
<Setter Property="FontStyle" Value="Italic" />
<Setter Property="Foreground" Value="Blue" />
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Viewbox Grid.Row="0" >
<TextBlock>This uses the default style</TextBlock></Viewbox>
<Viewbox Grid.Row="1">
<TextBlock Style="{StaticResource Specialization}">
This is the specialization
</TextBlock>
</Viewbox>
</Grid>
</Window>
这篇关于WPF 资源覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!