我在WPF DataGrid中显示数据,第一列显示静态文本“视图”。我添加了以下代码,以使文本看起来像一个按钮。我不想做很多工作来创建按钮列自定义模板。这几乎可以正常工作;文本居中,绘制边框。唯一不起作用的是背景没有出现-我仍然可以看到底层的交替行颜色。我还需要做其他事情来激活背景色吗,还是因为TextBlock嵌套在DataGridCell和其他对象(我认为)内而出现问题?
[我也尝试过使用TextBlock.BackgroundProperty创建Background setter,但这也不起作用。然后我尝试将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;
}
关于c# - 如何向DataGrid列单元格添加边框,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31755059/