How can I change the color of the gridlines of a Grid in WPF?

后端 未结 5 379
陌清茗
陌清茗 2020-12-15 17:17

I have a Grid (not a DataGrid, but a real Grid), with GridLines set to True. How can I change the color of the gridlines? Hardcoded in

5条回答
  •  死守一世寂寞
    2020-12-15 17:47

    Sorry, can't be done with ShowGridLines - you need to style the elements contained.

    Exhibit A:

    MSDN docs say "Only dotted lines are available because this property is intended as a design tool to debug layout problems and is not intended for use in production quality code. If you want lines inside a Grid, style the elements within the Grid to have borders."

    Exhibit B - The WPF Source Code:

    Notice the Brushes.Blue and Brushes.Yellow hard-coded in this sealed internal class which System.Windows.Controls.Grid uses to draw the lines.

    From Grid.cs

        /// 
        /// Helper to render grid lines. 
        /// 
        internal class GridLinesRenderer : DrawingVisual 
        { 
            /// 
            /// Static initialization 
            /// 
            static GridLinesRenderer()
            {
                s_oddDashPen = new Pen(Brushes.Blue, c_penWidth); 
                DoubleCollection oddDashArray = new DoubleCollection();
                oddDashArray.Add(c_dashLength); 
                oddDashArray.Add(c_dashLength); 
                s_oddDashPen.DashStyle = new DashStyle(oddDashArray, 0);
                s_oddDashPen.DashCap = PenLineCap.Flat; 
                s_oddDashPen.Freeze();
    
                s_evenDashPen = new Pen(Brushes.Yellow, c_penWidth);
                DoubleCollection evenDashArray = new DoubleCollection(); 
                evenDashArray.Add(c_dashLength);
                evenDashArray.Add(c_dashLength); 
                s_evenDashPen.DashStyle = new DashStyle(evenDashArray, c_dashLength); 
                s_evenDashPen.DashCap = PenLineCap.Flat;
                s_evenDashPen.Freeze(); 
            }
    

提交回复
热议问题