2012-02-29 60 views
1

我想写一个DataGridSeparatorColumn自定义控件,从DataGridColumn继承,强制它是2像素宽,并有黑色背景。从DataGridColumn继承的CustomControl:样式问题

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代码的示例,但我没有找到任何有用的东西。任何人都可以用正确的方式指点我吗

谢谢。

回答

0

试试这个:

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

PS:如果您希望列的标题也具有黑色,那么您可以通过设置DataGridColumnHeader.BackgroundProperty和列的HeaderStyle来做类似的事情。 – 2012-02-29 09:48:03

+0

它适用于'HeaderStyle',但不适用于'CellStyle':标题单元具有预期的黑色背景,但单元格不是。 – 2012-02-29 10:12:43

+0

我想Eirik说,你也必须设置一个-2的边距。否则,由于细胞太窄,无法看到黑色背景。 – 2012-02-29 10:21:11

1

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可能不是您的情况的完美值,所以在这里尝试不同的值,直到您满意为止。

+0

那么,我想说我的答案并不是要成为OP的要求的完整解决方案,只是一个正确方向的指针; StackOverflow是关于指导和理解,而不是其他人为你做你的工作!但无论如何,这足够公平。 – 2012-02-29 10:07:33

+0

这两个答案都很有用,顺便说一句,我会把@ bobsmith833的标记作为接受的标记 – 2012-02-29 11:05:50