Home > Software engineering >  How to change foreground color of selected Expander inside DataGrid TemplateColumn?
How to change foreground color of selected Expander inside DataGrid TemplateColumn?

Time:08-22

I have a problem with changing foreground color of Expander by using IsSelected property. I'm using code below, which works fine with Background property, but for some reason it doesn't work with Foreground.

<DataGrid.CellStyle>
    <Style TargetType="DataGridCell">
        <Style.Triggers>
            <Trigger Property="IsSelected" Value="True">
                <Setter Property="Background" Value="MediumSlateBlue"/>
                <Setter Property="Foreground" Value="White"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</DataGrid.CellStyle>

I added a few another fields and result is pretty strange: Picture

As you can see, even Label seems broken and only standard TextColumn and TemplateColumn with TextBlock inside it changed their foreground, though all of them applied a purple background. I think, the case may be that the Foreground property from Trigger is attached to the same property only inside some objects, but I'm clearly too young to understand how this works.

Would be grateful for any help. Here is the code of my DataGrid Columns if it will be useful to you:

<DataGrid.Columns>
    <!--Field with "Data in TextColumn"-->
    <DataGridTextColumn Header="TextColumn" Binding="{Binding Path=Name}" Width="170"/>

    <DataGridTemplateColumn Header="TextBlock" Width="150">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <TextBlock>Data in TextBlock</TextBlock>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>

    <DataGridTemplateColumn Header="Label" Width="150">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <Label>Data in Label</Label>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>

    <DataGridTemplateColumn Header="Expander" Width="250">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <Expander Header="Inside could be some objects"/>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
</DataGrid.Columns>

CodePudding user response:

According to: https://social.msdn.microsoft.com/Forums/en-US/8849add2-3ce0-4f0c-bfca-92defe0d8362/changing-forecolro-of-datagridtemlatecolumns-textboxes?forum=wpf

It seems more appropriate style is:

<TextBox.Style>
 <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
 <Setter Property="Foreground" 
    Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContentControl}}, Path=Foreground}" />
 </Style>
</TextBox.Style>
  • Related