MrProgrammer
MrProgrammer

Reputation: 709

WPF DataGrid: How do you set the style of the first row only?

I've tried searching for the answer, but the question that's been posted here has not been answered.

I've tried some complicated XAML, but it's never worked. The code below grays out all rows if the first row is selected. I need to gray out the first row only, regardless of which row index is selected.

<TextBlock.Style>
    <Style TargetType="TextBlock">
        <Setter Property="Foreground" Value="Black"/>
        <Setter Property="FontStyle" Value="Normal"/>
        <Style.Triggers>
            <MultiDataTrigger>
                <MultiDataTrigger.Conditions>
                    <Condition Binding="{Binding Path=SelectedIndex, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}}" Value="0"/>
                </MultiDataTrigger.Conditions>
                <Setter Property="Foreground" Value="Gray"/>
                <Setter Property="FontStyle" Value="Italic"/>
            </MultiDataTrigger>
        </Style.Triggers>
    </Style>
</TextBlock.Style>

Would anyone be able to help?

Thanks.

Upvotes: 2

Views: 2622

Answers (1)

Funk
Funk

Reputation: 11211

You can use the AlternationCount property found on all ItemsControls (ref ListBox).

<DataGrid ItemsSource="{Binding Items}"
          AlternationCount="2147483647"
          ... 
          >
    <DataGrid.ItemContainerStyle>
        <Style TargetType="DataGridRow">
            <Style.Triggers>
                <Trigger Property="ItemsControl.AlternationIndex" Value="0">
                    <Setter Property="Foreground" Value="Gray"/>
                    <Setter Property="FontStyle" Value="Italic"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </DataGrid.ItemContainerStyle>
    ...
</DataGrid>

EDIT

<DataGrid ItemsSource="{Binding Items}"
          AlternationCount="2"
          VirtualizingStackPanel.IsVirtualizing="False">
          ... 
          >
    <DataGrid.ItemContainerStyle>
        <Style TargetType="DataGridRow">
            <Style.Triggers>
                <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                    <Setter Property="Background" Value="Gray"/>
                </Trigger>
                <DataTrigger
                    Binding="{Binding RelativeSource={RelativeSource Mode=PreviousData}}"
                    Value="{x:Null}">
                    <Setter Property="Foreground" Value="Gray"/>
                    <Setter Property="FontStyle" Value="Italic"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.ItemContainerStyle>
    ...
</DataGrid>

Upvotes: 3

Related Questions