Habibur Rahman
Habibur Rahman

Reputation: 121

How to bind the color of a row in controls:DataGrid by binding with the value of a column in that row in UWP C#?

For a specific values in a row of a column, how to change the row background color in UWP C#>

I have used controls:DataGrid to show the values of a DataTable in UWP. I am trying to bind the color of a row based on a value in "Color" column of DataTable. If "Color" column is "Red" of a row, I have to set Row Background "Red", or green otherwise.

<controls:DataGrid.RowStyle>
    <Style TargetType="controls:DataGridRow">
        <Setter Property="Background" Value="{Binding ColumnForColorInDataTable}" />
    </Style>
</controls:DataGrid.RowStyle>

The code portion is from my xaml file.

Upvotes: 3

Views: 1606

Answers (1)

Anran Zhang
Anran Zhang

Reputation: 7727

XAML in UWP is different from WPF, and writing the bind content in the Setter does not take effect. Currently DataGrid belongs to community control, and there is still a gap between WPF's DataGrid. To achieve your goals, I recommend using ListView for a higher degree of personalization.

But with regard to your goal of changing the row background color. There is currently no direct way for the DataGrid to do this. But there is still a Hack method to achieve your purpose.

Each row of the DataGrid is composed of multiple cells. It is difficult to control a row accurately, but we can control the performance of each cell.

Suppose we have a Person class with a Name and ColumnForColorInDataTable properties.

<Page
    ...
    >
    <Grid>
        <controls:DataGrid AutoGenerateColumns="False" ItemsSource="{x:Bind PersonCollection}">
            <controls:DataGrid.Columns>

                <controls:DataGridTemplateColumn
                    Header="Name"
                    Width="SizeToHeader">

                    <controls:DataGridTemplateColumn.CellTemplate>
                        <DataTemplate x:DataType="Person">
                            <Border Background="{Binding ColumnForColorInDataTable}">
                                <TextBlock Text="{Binding Name}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                            </Border>
                        </DataTemplate>
                    </controls:DataGridTemplateColumn.CellTemplate>

                </controls:DataGridTemplateColumn>

                <!-- Other Columns-->

            </controls:DataGrid.Columns>
        </controls:DataGrid>
    </Grid>
</Page>

In this way, let a row of cells maintain the same color, disguised to achieve your purpose.

Best regards.

Upvotes: 2

Related Questions