Change the color of a row and cell in the DataGrid

Source: Internet
Author: User

When a WPF project was created some time ago, you needed to change the color and height of a row in the DataGrid, the color of a cell, and the font color of the cell. Naturally, you must obtain the cells of one row and one row in the DataGrid, it takes a long time to search for the Internet, so it is easy to use.

 

1. Add a DataGrid Control on the front-end WPF interface and add two columns (easy to write and achieve the goal)

<DataGrid AutoGenerateColumns="False" Height="642" HorizontalAlignment="Left" Margin="131,57,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="799" CanUserAddRows="True" LoadingRow="dataGrid1_LoadingRow" GridLinesVisibility="None">            <DataGrid.ColumnHeaderStyle >                <Style TargetType="DataGridColumnHeader">                    <Setter Property="Height" Value="50"></Setter>                </Style>            </DataGrid.ColumnHeaderStyle>            <DataGrid.Columns>                <DataGridTextColumn Header="id" Binding="{Binding Path=id}" ElementStyle="{StaticResource dgCell}"></DataGridTextColumn>                <DataGridTextColumn Header="name" Binding="{Binding Path=name}" ElementStyle="{StaticResource dgCell}"></DataGridTextColumn>            </DataGrid.Columns>        </DataGrid>
View code

 

2. Create and bind a data source. Here, create a datatable

DataTable dt = new DataTable();            dt.Columns.Add(new DataColumn("id", typeof(int)));            dt.Columns.Add(new DataColumn("name", typeof(string)));            for (int i = 0; i < 6; i++)            {                DataRow dr = dt.NewRow();                if (i == 3)                {                    dr["id"] = DBNull.Value;                    dr["name"] = DBNull .Value ;                    dt.Rows.Add(dr);                }                else                {                    dr["id"] = i;                    dr["name"] = "tom" + i.ToString();                    dt.Rows.Add(dr);                }            }            this.dataGrid1.CanUserAddRows = false;            this.dataGrid1.ItemsSource = dt.DefaultView;
View code

 

3. Obtain a single row

for (int i = 0; i < this.dataGrid1.Items.Count; i++)            {                DataRowView drv = dataGrid1.Items[i] as DataRowView;                DataGridRow row = (DataGridRow)this.dataGrid1.ItemContainerGenerator.ContainerFromIndex(i);                if (i == 2)                {                    row.Height = 50;                    row.Background = new SolidColorBrush(Colors.Blue);                    drv["id"] = 333;                }                if (drv["id"] == DBNull.Value)                {                    row.Background = new SolidColorBrush(Colors.Green);                    row.Height = 8;                }            }

 

4. Get Cells

for (int i = 0; i < this.dataGrid1.Items.Count; i++)            {                DataRowView drv = dataGrid1.Items[i] as DataRowView;                DataGridRow row = (DataGridRow)this.dataGrid1.ItemContainerGenerator.ContainerFromIndex(i);if (i == 4)                {                    DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);                    DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(1);                    cell.Background = new SolidColorBrush(Colors.Red);                }            }

public static T GetVisualChild<T>(Visual parent) where T : Visual { T childContent = default(T); int numVisuals = VisualTreeHelper.GetChildrenCount(parent); for (int i = 0; i < numVisuals; i++) { Visual v = (Visual)VisualTreeHelper.GetChild(parent, i); childContent = v as T; if (childContent == null) { childContent = GetVisualChild<T>(v); } if (childContent != null) { break; } } return childContent; }

 

5. If you create a data source, bind a data source, and operate the DataGrid (change the color and height of the row) in a project, an error occurred while retrieving the row of the DataGrid: the object is not referenced to the instance of the object.

Solution:

// Create and bind a data source

If (! Window. getwindow (datagrid1). isvisible) {window. getwindow (datagrid1). Show ();} datagrid1.updatelayout ();

// Obtain the cells of a row or row

 

Change the color of a row and cell in the DataGrid

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.