2009-05-12 9 views
9

많은 행과 열이 포함 된 WPF Grid가 있습니다. 모두 TextBlocks 및 TextBoxes를 포함합니다.WPF Grid - 단 하나의 열에 스타일을 적용하는 방법?

이 특정 상황에서 필자는 1 열의 모든 내용을 패딩으로 만들고 2 열의 모든 내용을 오른쪽 정렬해야합니다. 그리드의 각 항목에 해당 속성을 설정해야하는 것은 매우 비 WPF 인 것으로 보입니다.

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

하지만, 말에만 컨트롤에 열이를 그 스타일을 적용 할 수있는 방법이있다 :

은 내가 이런 일을 수행하여 그리드 내의 모든 TextBlocks의 스타일을 만들 수 있습니다 알아?

다른 컨트롤을 사용해야합니까?

+0

는 기본 그리드 제어 불가능합니다 .. 아마도 사용자 지정 연결된 속성을 사용하여 이와 유사한 작업을 수행 할 수 있습니다. –

답변

17

가 여기에 내가 일반적으로 할 수있는 작업은 다음과 같습니다

<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> 
+0

그게 내가 찾고 있던 바로 그거야! 멋지고 우아한, 왜 그렇게 생각하지 않았다 :) –

0

당신은 다음과 같은 몇 가지 스타일을 정의하고 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> 
+0

DataGrid 전용입니까? 이 방법을 그리드에 적용하는 방법을 알 수 없습니다. –

+0

각 열에 스타일을 지정할 수 있습니다. 편집 된 코드를 참조하십시오. – sacha

+0

표준 그리드로이 작업을 수행하는 방법을 찾고 있었지만 DataGrid를 살펴보고 대신이 작업을 사용할 수 있는지 확인합니다. –

관련 문제