C# 从DataGridColumn继承的CustomControl:样式设置问题

C# 从DataGridColumn继承的CustomControl:样式设置问题,c#,wpf,wpf-controls,C#,Wpf,Wpf Controls,我正试图编写一个DataGridSeparatorColumn自定义控件,该控件继承自DataGridColumn,强制其宽度为2像素,背景为黑色 public class DataGridSeparatorColumn : DataGridColumn { public DataGridSeparatorColumn() { CanUserReorder = false; CanUserResize = false; CanUse

我正试图编写一个DataGridSeparatorColumn自定义控件,该控件继承自DataGridColumn,强制其宽度为2像素,背景为黑色

public class DataGridSeparatorColumn : DataGridColumn
{
    public DataGridSeparatorColumn()
    {
        CanUserReorder = false;
        CanUserResize = false;
        CanUserSort = false;

        MaxWidth = 2;
        MinWidth = 2;

        IsReadOnly = true;

        Header = "";

        // TODO: Set black background and/or other visual stuff here                

    }

    protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
    {
        //return new FrameworkElement();
        return null;
    }

    protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
    {
        //return new FrameworkElement();
        return null;
    }
}
我在谷歌上到处搜索,想找到TODO代码的示例,但我没有找到任何有用的东西。谁能给我指路吗

谢谢。

试试这个:

Style myStyle = new Style();
Setter myBlackBackgroundSetter = new Setter();
myBlackBackgroundSetter.Property = DataGridCell.BackgroundProperty;
myBlackBackgroundSetter.Value = Brushes.Black;
myStyle.Setters.Add(myBlackBackgroundSetter);
CellStyle = myStyle;
试试这个:

Style myStyle = new Style();
Setter myBlackBackgroundSetter = new Setter();
myBlackBackgroundSetter.Property = DataGridCell.BackgroundProperty;
myBlackBackgroundSetter.Value = Brushes.Black;
myStyle.Setters.Add(myBlackBackgroundSetter);
CellStyle = myStyle;

bobsmith在正确的轨道上,但是您需要调整整个单元格颜色覆盖的边距(可能还有填充)属性

Style style = new Style(typeof(DataGridCell));
style.Setters.Add(new Setter(DataGridCell.BackgroundProperty, new SolidColorBrush(Colors.Black)));
style.Setters.Add(new Setter(DataGridCell.MarginProperty, new Thickness(-2.0)));

CellStyle = style;

-2.0对于您的情况可能不是完美的值,因此请在此处尝试不同的值,直到您满意为止。

bobsmith在正确的轨道上,但您需要调整整个单元格颜色的边距(可能还有填充)属性

Style style = new Style(typeof(DataGridCell));
style.Setters.Add(new Setter(DataGridCell.BackgroundProperty, new SolidColorBrush(Colors.Black)));
style.Setters.Add(new Setter(DataGridCell.MarginProperty, new Thickness(-2.0)));

CellStyle = style;

-2.0对于您的情况可能不是完美的值,因此请在此处尝试不同的值,直到您满意为止。

PS:如果您希望列标题也具有黑色,然后您可以通过设置DataGridColumnHeader.BackgroundProperty和列的HeaderStyle来执行类似的操作。它适用于
HeaderStyle
,但不适用于
CellStyle
:header单元格如预期的那样具有黑色背景,但单元格并非如此。我猜正如Eirik所说,您还必须将边距设置为-2。否则,由于单元格太窄,无法看到黑色背景。PS:如果希望列标题也具有黑色,然后您可以通过设置DataGridColumnHeader.BackgroundProperty和列的HeaderStyle来执行类似的操作。它适用于
HeaderStyle
,但不适用于
CellStyle
:header单元格如预期的那样具有黑色背景,但单元格并非如此。我猜正如Eirik所说,您还必须将边距设置为-2。否则黑色背景就看不见了,因为单元格太窄了。好吧,我想说我的答案并不是要完全解决OP的要求,只是一个指向正确方向的指针;StackOverflow是关于指导和理解的,而不是关于其他人为你工作的人!但无论如何,这也很公平。我想说,我的回答并不是要完全解决OP的要求,只是指向正确方向的指针;StackOverflow是关于指导和理解的,而不是关于其他人为你工作的人!但无论如何,这很公平。