WPF Grid - 如何为一列应用样式? [英] WPF Grid - How to apply a style for just one column?
问题描述
我有一个 WPF 网格,其中包含许多行和列,都包含诸如 TextBlocks 和 TextBoxes 之类的内容.
I have a WPF Grid with many rows and columns, all containing things like TextBlocks and TextBoxes.
对于这种特定情况,我希望第 1 列中的所有内容都有填充,并且第 2 列中的所有内容都正确对齐.必须在网格中的每个项目上设置这些属性似乎是非常非 WPF 的.
For this specific situation I want all the stuff in column 1 to have padding, and all the stuff in column 2 to be aligned right. It seems to be very non-WPF to have to set those properties on each item in the grid.
我知道我可以通过执行以下操作为网格中的所有 TextBlocks 创建样式:
I know I can create a style for all TextBlocks within a grid by doing something like this:
<Grid>
<Grid.Resources>
<Style TargetType="{x:Type TextBox}">
<Setter Property="HorizontalAlignment" Value="Right"/>
</Style>
</Grid.Resources>
</Grid>
但是有没有办法将该样式仅应用于第 2 列中的控件?
But is there a way to apply that style to only the controls in say, column 2?
我应该使用不同的控件吗?
Should I be using a different control?
推荐答案
这是我通常做的:
<Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource {x:Type TextBlock}}">
<Style.Triggers>
<Trigger Property="Grid.Column" Value="0">
<Setter Property="Margin" Value="0,0,2,0" />
</Trigger>
<Trigger Property="Grid.Column" Value="2">
<Setter Property="Margin" Value="20,0,2,0" />
</Trigger>
</Style.Triggers>
</Style>
这篇关于WPF Grid - 如何为一列应用样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!