2012-11-06 3 views
0

WPF DataGrid가 있는데 observablecollection으로 바인딩했습니다. 그것은 잘 작동하지만 문제는 런타임에 셀 수준에서 스타일을 적용한다는 것입니다. 아래에 언급 된 샘플 메소드 인 ApplyStyleAtCellLevelInDataGrid()가 있습니다. WPF DataGrid에서 스타일 효과를 나타 내기 위해이 메서드를 두 번 호출해야합니다. "{: 유형 DataGridCell X}">WPF Datagrid의 WPF 스타일 문제

 <Setter Property="BorderThickness" Value="0" /> 
     <Setter Property="FontSize" Value="10"></Setter> 
     <Setter Property="Foreground" Value="Black"></Setter>   
    </Style> 

그리드 선언 키 = "DGCellStyle"은 TargetType = 왜 그렇게 ... 여기

는 XAML

<Style x:Key="BaseStyle" TargetType="{x:Type TextBlock}"> 
    <Setter Property="Background" Value="Transparent"/> 
    <Setter Property="Foreground" Value="Black"/>   
    <Setter Property="FontSize" Value="10"/> 
    <Setter Property="TextAlignment" Value="Center"/> 
</Style> 

<Style TargetType="{x:Type TextBlock}" x:Key="Col1Style" BasedOn="{StaticResource BaseStyle}"> 

     <Setter Property="Background"> 
      <Setter.Value> 
       <SolidColorBrush Color="Tomato"/> 
      </Setter.Value> 
     </Setter>    

     <Style.Triggers> 
      <EventTrigger RoutedEvent="Binding.TargetUpdated"> 
       <BeginStoryboard HandoffBehavior="Compose"> 
        <Storyboard TargetProperty="(TextBlock.Background).(SolidColorBrush.Color)"> 
        <ColorAnimation Duration="0:0:1.5" To="DarkRed" AutoReverse="True" RepeatBehavior="1" /> 
        </Storyboard> 
       </BeginStoryboard> 
      </EventTrigger> 
     </Style.Triggers> 
    </Style> 

< 스타일 x는 XAML

에서
<DataGrid Name="dataGrid1" ItemsSource="{Binding Values}" CellStyle="{StaticResource DGCellStyle}" SnapsToDevicePixels="True" UseLayoutRounding="False"> 

    <DataGrid.Columns> 
     <DataGridTextColumn Header="Value" Binding="{Binding Value1, Mode=OneWay, NotifyOnTargetUpdated=True}" Width="0.25*"/> 
     <DataGridTextColumn Header="Value 1" Binding="{Binding Value2, Mode=OneWay, NotifyOnTargetUpdated=True}" Width="0.25*"/> 
     <DataGridTextColumn Header="Value 2" Binding="{Binding Value3, Mode=OneWay, NotifyOnTargetUpdated=True}" Width="0.25*"/> 
     <DataGridTextColumn Header="Value 3" Binding="{Binding Value4, Mode=OneWay, NotifyOnTargetUpdated=True}" Width="0.25*"/> 
    </DataGrid.Columns>   
</DataGrid> 

코드

private void ApplyStyleAtCellLevelInDataGrid() 

    { 
     if (Values == null || Values.Count == 0) 
     { 
      Values = new ObservableCollection<MyClass>(); 
      Values.Add(new MyClass { Value1 = "1", Value4 = "2", Value2 = "4", Value3 = "3" }); 
      Values.Add(new MyClass { Value1 = "2", Value4 = "3", Value2 = "5", Value3 = "7" }); 
      Values.Add(new MyClass { Value1 = "3", Value4 = "4", Value2 = "7", Value3 = "2" }); 
      Values.Add(new MyClass { Value1 = "4", Value4 = "4", Value2 = "8", Value3 = "6" }); 
     } 
     else 
     { 
      foreach (var item in Values) 
      { 
       MyClass c = item as MyClass; 
       c.Value1 = _rand.Next(0, 100).ToString();   
       c.Value2 = _rand.Next(0, 100).ToString(); 
       c.Value3 = _rand.Next(0, 100).ToString(); 
       c.Value4 = _rand.Next(0, 100).ToString(); 
      } 
     } 

     ////////////// 

     DataGridCell cell = GetCell(1, 1); 

     Style defaultStyle = (Style)FindResource("NewStyle"); 
     ((TextBlock)cell.Content).Style = defaultStyle; 

     cell = GetCell(1, 2); 
     defaultStyle = (Style)FindResource("NewStyleExtended"); 
     ((TextBlock)cell.Content).Style = defaultStyle; 

     cell = GetCell(2, 2); 
     defaultStyle = (Style)FindResource("NewStyle"); 
     ((TextBlock)cell.Content).Style = defaultStyle; 

     cell = GetCell(2, 3); 
     defaultStyle = (Style)FindResource("Col1Style"); 
     ((TextBlock)cell.Content).Style = defaultStyle; 
    } 


private void Window_Loaded(object sender, RoutedEventArgs e) 
    {   
// Single call of this method does not work, 

I have to call two times then it shows the effect 

     ApplyStyleAtCellLevelInDataGrid(); 
     ApplyStyleAtCellLevelInDataGrid(); 
    } 

답변

0

스타일의 TargetTypeTextBlock에서 DataGridCell으로 변경 한 다음 스타일을 DataGrid.CellStyle으로 적용하십시오. CellStyle을 이미 DGCellStyle으로 설정 했으므로 두 스타일을 병합해야 할 것입니다. TextAlignment 당신은 DataTemplateSelector 구현에 관심이있을 수 DataGridCell

<Style x:Key="BaseStyle" TargetType="{x:Type DataGridCell}"> 
    <Setter Property="Background" Value="Transparent"/> 
    <Setter Property="Foreground" Value="Black"/>   
    <Setter Property="FontSize" Value="10"/> 
    <Setter Property="HorizontalAlignment" Value="Center"/> 
</Style> 

<Style TargetType="{x:Type DataGridCell}" x:Key="Col1Style" BasedOn="{StaticResource BaseStyle}"> 
    <Setter Property="Background"> 
     <Setter.Value> 
      <SolidColorBrush Color="Tomato"/> 
     </Setter.Value> 
    </Setter>    

    <Style.Triggers> 
     <EventTrigger RoutedEvent="Binding.TargetUpdated"> 
      <BeginStoryboard HandoffBehavior="Compose"> 
       <Storyboard TargetProperty="(DataGridCell.Background).(SolidColorBrush.Color)"> 
       <ColorAnimation Duration="0:0:1.5" To="DarkRed" AutoReverse="True" RepeatBehavior="1" /> 
       </Storyboard> 
      </BeginStoryboard> 
     </EventTrigger> 
    </Style.Triggers> 
</Style> 

그리고

<DataGrid CellStyle="{StaticResource Col1Style}" ... /> 
+0

감사를 AutoGeneratedColumns 이벤트를 추가로 뒤에 코드 지금

<Style x:Key="ColumnHeaderStyle" TargetType="{x:Type dg:DataGridColumnHeader}"> <Setter Property="HorizontalAlignment" Value="Center" /> </Style> <Style x:Key="CellRightAlign" TargetType="{x:Type dg:DataGridCell}"> <Setter Property="HorizontalAlignment" Value="Right" /> </Style> 

를 추가하지만 내 메일 질문은 왜 내가 전화를한다는 것입니다 ApplyStyleAtCellLevelInDataGrid() ; 스타일의 효과를 보여주기 위해 Window_Loaded 이벤트에서 2 번? 한 번 호출하면 화면에 아무 것도 표시되지 않습니다. –

+0

@ AsadNaeem 가장 좋은 추측은 WPF의 [DispatcherPriority] (http://msdn.microsoft.com/en-us/library/system.windows.threading)와 관련이 있다는 것입니다. dispatcherpriority.aspx), 첫 번째 실행은'Grid'가 바인드 된'Values' 콜렉션을 생성하고 DataGrid 아이템이 렌더링을 끝내지 않았거나 렌더 패스와 덮어 쓰기 중에 기본 스타일이 적용된다는 것입니다 당신의 커스텀 스타일, 그래서 2 번째 런스가 필요한 이유입니다. 테스트 시나리오를 설정하지 않고는 확실히 알 수 없습니다. – Rachel

0

의 속성이 아니므로

또한, 당신은 당신의 기본 스타일에 HorizontalAlignmentTextAlignment을 변경해야합니다 . 이 개체는 모든 데이터 항목에 대한 표시 논리를 제공하는 데 사용됩니다. App.xaml에서 http://www.switchonthecode.com/tutorials/wpf-tutorial-how-to-use-a-datatemplateselector

+0

답변 주셔서 감사하지만 내 메일 질문은 왜 내가 ApplyStyleAtCellLevelInDataGrid(); 스타일의 효과를 보여주기 위해 Window_Loaded 이벤트에서? 한 번 호출하면 화면에 아무 것도 표시되지 않습니다. –

+0

잘 모르겠습니다.하지만 WPF에는 사용자 지정 논리를 기반으로 스타일을 수정하기위한 인터페이스가 있으며 사용자는이를 사용하지 않습니다. 내 답변은 : 아마도 당신이 처분에 주위에 다니는 대신 도구를 사용하는 경우, 당신은 심지어 "ApplystyleAtCellLevel"기능이 필요하지 않을 것입니다. – Joe

0

이 응용 프로그램 태그에

"xmlns:dg="http://schemas.microsoft.com/wpf/2008/toolkit"을 추가

여기에 빠른 튜토리얼입니다. <Application.Resources>에서

태그는 데이터 그리드에 대한 답변에 대한

Style RightAlign = (Style)FindResource("CellRightAlign"); 
yourGrid.Columns[0].CellStyle = RightAlign;