0
votes

I have a WPF datagrid and i have bound it with an observablecollection. It is working fine but the issue is that I have apply the styles at cell level at runtime. There is a sample method ApplyStyleAtCellLevelInDataGrid() which is mentioned below. I have to call this method two times to show the effect of styles in WPF DataGrid. Why is it so...

Here is 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>

< Style x:Key="DGCellStyle" TargetType="{x:Type DataGridCell}">

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

Grid Declaration in 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>

Code

 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();
    }
3

3 Answers

0
votes

Change your Style's TargetType from a TextBlock to a DataGridCell, then apply the style as the DataGrid.CellStyle. Since you already have a CellStyle set to DGCellStyle, you'll probably have to merge the two styles.

Also, you'll need to change TextAlignment to HorizontalAlignment in your base style since TextAlignment is not a property of 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>

And

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

You might be interested in implementing a DataTemplateSelector. This object is used to provide the display logic on any data item.

Here's a quick tutorial: http://www.switchonthecode.com/tutorials/wpf-tutorial-how-to-use-a-datatemplateselector

0
votes

In App.xaml add

"xmlns:dg="http://schemas.microsoft.com/wpf/2008/toolkit" in Application tag.

In <Application.Resources> tag add

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

Now in code behind of add AutoGeneratedColumns event to your datagrid

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