WPF网格 - 如何为一列应用样式? [英] WPF Grid - How to apply a style for just one column?

查看:141
本文介绍了WPF网格 - 如何为一列应用样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含许多行和列的WPF Grid,它们都包含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?

推荐答案

do:

Here's what I usually do:

<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网格 - 如何为一列应用样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆