更改ListView标题和网格线颜色

时间:2013-08-17 00:06:59

标签: c# winforms

我有一个Windows窗体应用程序,其中我添加了几个listViews以便为用户保存一些数据,它看起来像这样

enter image description here

当你看到我的表格背景颜色为黑色时,列表视图的网格线和标题白色会产生令人讨厌的对比,所以经过一个小时的搜索没有运气我决定在这里问。

[问题]:如何编辑Header&的颜色?列表视图的网格线符合我的需求?

2 个答案:

答案 0 :(得分:8)

看起来没有人有兴趣自定义ListView以支持Grid Line Color。我试过这个,想在这里分享一下。滚动ListView项目时,有点闪烁(不是很多)并不是很好。不过这是可以接受的。我认为我在这里缺乏一些win32的知识,以使其更加完美:

public class CustomListView : ListView {
        bool scrollDown;
        int lastScroll;
        public Color GridLinesColor {get;set;}
        [DllImport("user32")]
        private static extern int GetScrollPos(IntPtr hwnd, int nBar);
        public CustomListView(){
           GridLinesColor = Color.Red;
           DoubleBuffered = true;
           base.GridLines = false;//We should prevent the default drawing of gridlines.
        }
        public new bool GridLines {get;set;}
        protected override void WndProc(ref Message m)
        {                
            if (m.Msg == 0x20a){//WM_MOUSEWHEEL = 0x20a
                scrollDown = (m.WParam.ToInt64() >> 16) < 0;
            }
            if (m.Msg == 0x115){//WM_VSCROLL = 0x115
                int n = (m.WParam.ToInt32() >> 16);
                scrollDown = n > lastScroll;
                lastScroll = n;
            }                
            base.WndProc(ref m);
            if (m.Msg == 0xf && GridLines && Items.Count > 0&&View==View.Details)//WM_PAINT = 0xf
            {                    
                using (Graphics g = CreateGraphics())
                {
                    using(Pen p = new Pen(GridLinesColor)){
                      int w = -GetScrollPos(Handle, 0);
                      for (int i = 0; i < Columns.Count; i++)
                      {
                        w += Columns[i].Width;
                        g.DrawLine(p, new Point(w, 0), new Point(w, ClientSize.Height));
                      }
                      int a = Items[0].Bounds.Bottom - 1;
                      int b = Height - Items[0].Bounds.Y;
                      int c = Items[0].Bounds.Height;
                      for (int i = scrollDown ? a + (b/c) * c : a ; scrollDown ? i >= a : i < b ; i += scrollDown ? -c : c)
                      {
                        g.DrawLine(p, new Point(0, i), new Point(ClientSize.Width, i));
                      }                                      
                    }          
                }                 
            }

        }
}

更新:感谢Cody Gray的建议,我添加了处理水平滚动的代码。为简单起见,我使用GetScrollPos,因为根据MSDN文档页面的建议,我们应该使用GetScrollInfo

enter image description here

答案 1 :(得分:-1)

你可以在DataGrid中执行它,但我不认为ListView有一个简单的方法,因为与DataGrid不同,这些行没有属性。

<Style TargetType="{x:Type DataGrid}">
    <Setter Property="HorizontalGridLinesBrush" Value="Red"/>
    <Setter Property="VerticalGridLinesBrush" Value="Green"/>
</Style>

将其放入应用程序资源或窗口资​​源中。

除此之外,还有一种方法可以更改每个ListViewItem的边框颜色:

<Style TargetType="{x:Type ListViewItem}">
    <Setter Property="BorderBrush" Value="Red"/>
</Style>