我的wpf应用程序中存在一个小问题。我有两个课程GameObject
和Block
。两者都是CustomControl
s,GameObject
直接来自Control
,Block
来自GameObject
。我想写一个基于GameObject
样式的样式。这是一段代码
<Style TargetType="{x:Type primitives:GameObject}" x:Key="game">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type primitives:GameObject}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Grid.Row" Value="{Binding Path=Row, RelativeSource={RelativeSource Self}}"/>
<Setter Property="Grid.Column" Value="{Binding Path=Column, RelativeSource={RelativeSource Self}}"/>
</Style>
<Style TargetType="{x:Type primitives:Block}" BasedOn="{StaticResource game}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type primitives:Block}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
但是,如果我在第一个样式中添加x:Key
,它将不会自动应用于GameObject
的每个实例,因此我的Style在程序中的其他文件中无用。任何想法该怎么做?
答案 0 :(得分:3)
你仍然可以将它应用于所有特定的,你只需要一种可以反映它的全局风格。
<Style TargetType="{x:Type primitives:GameObject}" x:Key="game">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type primitives:GameObject}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Grid.Row" Value="{Binding Path=Row, RelativeSource={RelativeSource Self}}"/>
<Setter Property="Grid.Column" Value="{Binding Path=Column, RelativeSource={RelativeSource Self}}"/>
</Style>
<Style TargetType="{x:Type primitives:Block}" BasedOn="{StaticResource game}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type primitives:Block}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="{x:Type primitives:GameObject}" BasedOn="{StaticResource game}">
</Style>
如果您需要在范围(object.resources)或全局范围内应用命名样式,则基于OnOn有一定的可能性。