我有这样的 TextBlock
风格:
<Style TargetType="TextBlock" x:Key="FormLabel">
<Setter Property="Height" Value="20" />
<Setter Property="Margin" Value="10" />
<Setter Property="TextAlignment" Value="Right" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
我以基于
Grid
的形式使用它,例如:<TextBlock Text="Code" Grid.Row="1" Grid.Column="0" Style="{StaticResource FormLabel}" />
现在,我不想在网格中的每个
TextBlock
上重复样式名称,而是更喜欢例如有一个 Grid
风格,如:<Style TargetType="Grid" x:Key="FormGrid">
<Setter Property="Width" Value="400" />
...
</Style>
然后,如果可能的话,我想修改我的
TextBlock
样式,使其仅在该元素是 Grid
样式的 FormGrid
的子元素时才适用于该元素。这可能吗,如果可以,我该如何实现?
最佳答案
通过在另一种样式中使用隐式样式作为资源,这确实是可能的。拿这个例子:
...
<Window.Resources>
<Style x:Key="FormGrid" TargetType="Grid">
<Style.Resources>
<Style TargetType="TextBlock">
<Setter Property="Height" Value="20" />
<Setter Property="Margin" Value="10" />
<Setter Property="TextAlignment" Value="Right" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</Style.Resources>
<Setter Property="Width" Value="400" />
</Style>
</Window.Resources>
<StackPanel>
<Grid Style="{StaticResource FormGrid}">
<TextBlock Text="This text block is styled with FormGrid TextBlock implicit style."/>
</Grid>
<TextBlock Text="This text block uses the default style."/>
</StackPanel>
...
关于wpf - 我可以将 WPF 样式仅应用于特定布局中的元素吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41942763/