WPF Datagrid trigger row colour based on value

后端 未结 1 1496
无人及你
无人及你 2021-01-06 01:30

I have a WPF application that contains a datagrid. The datagrid is bound to my object OrderBlock which contains a List of type Orders.



        
相关标签:
1条回答
  • 2021-01-06 02:14

    Do you need to change the behaviour of the DataGridRow, or is it sufficient to alter the style?

    If changing the row highlighting based on a property is all you need, you should be able to just use a simpler Style, something like this:

        <!-- A brush -->
        <LinearGradientBrush x:Key="BgBrush1" StartPoint="0,0" EndPoint="0,1">
            <GradientStop Offset="0" Color="#888888"/>
            <GradientStop Offset="1" Color="#FFFFF86E"/>
        </LinearGradientBrush>
    
        <!-- Your row style -->
        <Style x:Key="HighlightRow" TargetType="{x:Type DataGridRow}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding StatusGood}" Value="Hold">
                    <Setter Property="Background" Value="{StaticResource BgBrush1}" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    

    You should be able to apply the style when required in a DataGrid by using your style as a StaticResource for the RowStyle property:

    <DataGrid DataContext="{Binding OrderBlock}"
              Name="dataGridOrdersGood" 
              ItemsSource="{Binding Orders}" 
              RowStyle="{StaticResource HighlightRow}" />
    

    Edit:

    If you want to retain the rest of your styling and use a control template, you can place your DataTrigger in your ControlTemplate.Triggers, you'll also have to supply a TargetName property, to specify the element you wish the trigger to act on, so using my above brush, and your initial code:

    <!-- Data grid formatting Grid Row template -->
    <Style x:Key="DG_Row" TargetType="{x:Type DataGridRow}">        
        <Setter Property="Template">            
            <Setter.Value>
            <!-- Your code -->
                <ControlTemplate TargetType="{x:Type DataGridRow}">
                    <Border x:Name="DGR_Border"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            SnapsToDevicePixels="True">
                    <!-- Your code -->
                    </Border>
                    <ControlTemplate.Triggers>
                        <DataTrigger Binding="{Binding StatusGood}" Value="Send">
                            <Setter TargetName="DGR_Border" Property="Background" Value="{StaticResource BgBrush1}"/>
                         </DataTrigger>
                     </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    

    Where DGR_Border is the name you had given your border with the existing gradient.

    0 讨论(0)
提交回复
热议问题