[英]How To Add A Border To DataGrid Column Cells
我在 WPF DataGrid 中顯示數據,第一列顯示靜態文本“View”。 我添加了下面的代碼,使文本看起來像一個按鈕。 我不想做很多工作來創建按鈕列自定義模板。 這幾乎是有效的; 文本居中,邊框繪制。 唯一不工作的是背景沒有出現 - 我仍然可以看到底層交替的行顏色。 我還需要做些什么來激活背景顏色,還是因為 TextBlock 嵌套在 DataGridCell 和(我認為)其他一些對象中而出現問題?
[我也試過用 TextBlock.BackgroundProperty 創建背景設置器,但這也不起作用。 我嘗試將 BackgroundProperty 設置為 ImageBrush,這會更好,但它找不到我的圖像位置。]
private void dgvDetail_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) { string sHeader = e.Column.Header.ToString(); if (sHeader.Trim().ToLower() == "view") { e.Column.CellStyle = GetViewColumnStyle(); } } private Style GetViewColumnStyle() { Style oStyle = new Style(typeof(DataGridCell)); Setter oTextAlignment = new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Center); oStyle.Setters.Add(oTextAlignment); Setter oBackground = new Setter(DataGridCell.BackgroundProperty, Brushes.LightGray); oStyle.Setters.Add(oBackground); Setter oForeground = new Setter(DataGridCell.ForegroundProperty, Brushes.Black); oStyle.Setters.Add(oForeground); Setter oBorderBrush = new Setter(DataGridCell.BorderBrushProperty, Brushes.Black); oStyle.Setters.Add(oBorderBrush); Setter oMargin = new Setter(DataGridCell.MarginProperty, new Thickness(2, 2, 2, 2)); oStyle.Setters.Add(oMargin); return oStyle; }
您只是在為里面的TextBlock
樣式。 您應該設置DataGridCell.Template
:
private Style GetViewColumnStyle()
{
// The TextBlock
FrameworkElementFactory textBlockFactory = new FrameworkElementFactory(typeof(TextBlock));
// DataBinding for TextBlock.Text
Binding textBinding = new Binding("YourTextBindingPath");
textBlockFactory.SetValue(TextBlock.TextProperty, textBinding);
//Other TextBlock attributes
textBlockFactory.SetValue(TextBlock.TextAlignmentProperty, TextAlignment.Center);
textBlockFactory.SetValue(TextBlock.BackgroundProperty, Brushes.LightGray);
textBlockFactory.SetValue(TextBlock.ForegroundProperty, Brushes.Black);
textBlockFactory.SetValue(TextBlock.MarginProperty, new Thickness(2, 2, 2, 2));
// The Border around your TextBlock
FrameworkElementFactory borderFactory = new FrameworkElementFactory(typeof(Border));
borderFactory.SetValue(Border.BorderBrushProperty, Brushes.Black);
borderFactory.SetValue(Border.BorderThicknessProperty, new Thickness(1, 1, 1, 1));
// Add The TextBlock to the Border as a child element
borderFactory.AppendChild(textBlockFactory);
// The Template for each DataGridCell = your Border that contains your TextBlock
ControlTemplate cellTemplate = new ControlTemplate();
cellTemplate.VisualTree = borderFactory;
// Setting Style.Template
Style oStyle = new Style(typeof(DataGridCell));
Setter templateSetter = new Setter(DataGridCell.TemplateProperty, cellTemplate);
oStyle.Setters.Add(templateSetter);
return oStyle;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.