Click here to Skip to main content
15,400,433 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to set a style for my DataGrid, but I do not know where is the problem
the backgroud property does not work with its value in the presence of the Template property.

my code:

        <Style x:Key="DataGridStyle1" TargetType="{x:Type DataGrid}">
            <Setter Property="CellStyle" Value="{DynamicResource GridStyle1}"/>

<Style x:Key="GridStyle1" TargetType="DataGridCell">
                <Trigger Property="IsSelected" Value="True" >
                    <Setter Property="Background" Value="SeaGreen"/>
            <Setter Property="Template">

                    <ControlTemplate TargetType="{x:Type DataGridCell}">
                        <Border Name="DataGridCellBorder">
                            <ContentControl Content="{TemplateBinding Content}">

<TextBlock Background="Transparentquot; TextWrapping="WrapWithOverflow" TextTrimming="CharacterEllipsis" Height="auto" Width="auto" Text="{Binding Text}"/>

<DataGrid Style="{DynamicResource DataGridStyle1}" AutoGenerateColumns="True" SelectionChanged="grid_Pr_SelectionChanged"/>

Help me please.


1 solution

I cannot tell you the reasons it works the way it does, but I can help you fix what is wrong. Essentially, your template is overriding your cell style.

I bet if you remove the whole template section it'll work. But, assuming you want the behavior, you'll have to add it within the control template. The binding is a little more complicated.
    <TextBlock TextWrapping="WrapWithOverflow"
                TextTrimming="CharacterEllipsis" Height="Auto" Width="Auto"
                Text="{Binding Text}">
            <Style TargetType="{x:Type TextBlock}">
                    <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGridCell}}}" Value="True">
                        <Setter Property="Background" Value="SeaGreen" />

P.S. You should be using StaticResource not DynamicResource. You don't need it here, and you're incurring a little more overhead because of it.
nasrsoft 2-Mar-14 23:37pm
thanks it works..
tgrt 3-Mar-14 8:07am
Glad to hear it!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900