C#完成轉變DataGrid某一行和單位格色彩的辦法。本站提示廣大學習愛好者:(C#完成轉變DataGrid某一行和單位格色彩的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#完成轉變DataGrid某一行和單位格色彩的辦法正文
本文所述實例重要完成WPF項目中C#轉變DataGrid某一行和單位格色彩的功效。分享給年夜家供年夜家參考。詳細辦法以下:
假如要轉變DataGrid某一行的色彩、高度,和某個單位格的色彩、單位格字體的色彩,就必須取到datagrid的一行和一行的單位格,經由過程查找相干材料及測試總結出以下實例代碼,現記載上去便於年夜家參考應用。
1、前台WPF界面添加一個DataGrid控件,並添加兩列(便於編寫,到達目標便可)
<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}" Element></DataGridTextColumn> <DataGridTextColumn Header="name" Binding="{Binding Path=name}" Element></DataGridTextColumn> </DataGrid.Columns> </DataGrid>
2、創立一個數據源並綁定,此處是創立一個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;
3、獲得單行
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、獲得單位格
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、假如在項目中把創立數據源、綁定命據源、對datagrid停止操作(轉變行的色彩、高度)都寫在一個事宜中,個中在取datagrid的row時湧現毛病:未將對象援用設置到對象的實例。
處理的辦法:
//創立數據源、綁定命據源 if (!Window.GetWindow(dataGrid1).IsVisible) { Window.GetWindow(dataGrid1).Show(); } dataGrid1.UpdateLayout(); //可以獲得某一行、某一行的單位格
信任本文所述對年夜家的C#法式設計有必定的自創感化。