WPF 后台添加DataGrid
2016-04-15 10:02 孙启亮 阅读(3276) 评论(0) 编辑 收藏 举报public DataGrid CreateDataGrid() { //自定义DataGrid DataGrid dataGrid = null; dataGrid = new DataGrid(); dataGrid.Height = 340; dataGrid.Margin = new Thickness(10, 30, 0, 0); dataGrid.IsReadOnly = true; dataGrid.AutoGenerateColumns = false; dataGrid.CanUserResizeColumns = false; System.Windows.Data.Binding binding = null; binding = new System.Windows.Data.Binding("E_ID"); binding.Mode = System.Windows.Data.BindingMode.OneWay; DataGridTextColumn dgtcE_Id = null; dgtcE_Id = new DataGridTextColumn(); dgtcE_Id.Header = "列头1"; dgtcE_Id.Width = 70; dgtcE_Id.Visibility = Visibility.Collapsed; dgtcE_Id.Binding = binding; dataGrid.Columns.Add(dgtcE_Id); binding = new System.Windows.Data.Binding("E_Type"); binding.Mode = System.Windows.Data.BindingMode.OneWay; DataGridTextColumn dgtcE_Type = null; dgtcE_Type = new DataGridTextColumn(); dgtcE_Type.Header = "列头2"; dgtcE_Type.Width = 200; dgtcE_Type.Binding = binding; dataGrid.Columns.Add(dgtcE_Type); binding = new System.Windows.Data.Binding("E_TypeName"); binding.Mode = System.Windows.Data.BindingMode.OneWay; DataGridTextColumn dgtcE_TypeName = null; dgtcE_TypeName = new DataGridTextColumn(); dgtcE_TypeName.Header = "列头3"; dgtcE_TypeName.Width = 200; dgtcE_TypeName.Binding = binding; dataGrid.Columns.Add(dgtcE_TypeName); binding = new System.Windows.Data.Binding("E_State"); binding.Mode = System.Windows.Data.BindingMode.OneWay; DataGridTextColumn dgtcReveaState = null; dgtcReveaState = new DataGridTextColumn(); dgtcReveaState.Header = "列头4"; dgtcReveaState.Width = 120; dgtcReveaState.Binding = binding; dataGrid.Columns.Add(dgtcReveaState); //DataGrid中Column的内容居中 Style styleRight = new Style(typeof(TextBlock)); Setter setRight = new Setter(TextBlock.HorizontalAlignmentProperty, HorizontalAlignment.Center); styleRight.Setters.Add(setRight); foreach (DataGridColumn c in dataGrid.Columns) { DataGridTextColumn tc = c as DataGridTextColumn; if (tc != null) { tc.ElementStyle = styleRight; } } //表头居中 Style style = new Style(typeof(DataGridColumnHeader)); setRight = new Setter(DataGridColumnHeader.HorizontalContentAlignmentProperty, HorizontalAlignment.Center); style.Setters.Add(setRight); dataGrid.ColumnHeaderStyle = style; return dataGrid; }
设置满足某条件行的背景色
private void datagrid_LoadingRow(object sender, DataGridRowEventArgs e) { var drv = e.Row.Item as DataRowView; switch (drv["ID"].ToString()) { case "1": e.Row.Background = new SolidColorBrush(Colors.Green); break; case "2": e.Row.Background = new SolidColorBrush(Colors.Yellow); break; case "3": e.Row.Background = new SolidColorBrush(Colors.CadetBlue); break; } }
。