15

多くの行と列を含むWPFグリッドがあり、すべてにTextBlocksやTextBoxesなどが含まれています。

この特定の状況では、列1のすべてのものにパディングを付け、列2のすべてのものを正しく配置する必要があります。グリッド内の各アイテムにこれらのプロパティを設定する必要があるのは、WPFではないようです。

次のような操作を行うことで、グリッド内のすべてのTextBlockのスタイルを作成できることを知っています。

<Grid>
  <Grid.Resources>
    <Style TargetType="{x:Type TextBox}">
      <Setter Property="HorizontalAlignment" Value="Right"/>
    </Style>
  </Grid.Resources>
</Grid>

しかし、そのスタイルを、たとえば列2のコントロールのみに適用する方法はありますか?

別のコントロールを使用する必要がありますか?

4

2 に答える 2

24

これが私が通常行うことです:

<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>
于 2009-05-12T14:28:21.047 に答える
1

以下のようないくつかのスタイルを定義して、Column.ElementStyle プロパティに割り当てることができます。

<Window.Resources>
       <Style x:Key="elementStyle" TargetType="TextBlock">
           <Setter Property="VerticalAlignment" Value="Center" />
           <Setter Property="Margin" Value="2,0,2,0" />
       </Style>

       <Style x:Key="rightElementStyle" BasedOn="{StaticResource elementStyle}" TargetType="TextBlock">
           <Setter Property="HorizontalAlignment" Value="Right" />
       </Style>

       <Style x:Key="centerElementStyle" BasedOn="{StaticResource elementStyle}" TargetType="TextBlock">
           <Setter Property="HorizontalAlignment" Value="Center" />
       </Style>
</Window.Resources>

<dg:DataGrid AutoGenerateColumns="False">
      <dg:DataGrid.Columns>
           <dg:DataGridTextColumn Binding={Binding Path=Name} 
                                  Header="Name" 
                                  ElementStyle="{StaticResource centerElementStyle}"/>
           <dg:DataGridTextColumn Binding={Binding Path=Amount} 
                                  Header="Amount" 
                                  ElementStyle="{StaticResource rightElementStyle}"/>
    </dg:DataGrid.Columns>
</dg:DataGrid>
于 2009-05-12T08:41:31.160 に答える