如何在c#Winform App中将复选框添加到列表视图列标题? [英] How to Add a Checkbox to a List View Column Header in c# Winform App?

查看:291
本文介绍了如何在c#Winform App中将复选框添加到列表视图列标题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在标题中添加复选框,如果我选中了标题复选框,也应该像全选一样,然后取消选择所有...就像上图所示!

I want to add checkbox in header and also if I checked in header checkbox it should be like select all and deselect All... just like above image!

我想用c#中的复选框创建这种类型的listview标头

I want to create this type of listview header with checkbox in c#

推荐答案

您可以设置 OwnerDraw 属性设置为true,并在第一列标题上绘制ChceckBox并按ColumnClick键执行全部选择/取消选择操作.

You can set OwnerDraw property of ListView to true and draw a ChceckBox on first column header and handle ColumnClick to perform select/deselect all.

  • 要绘制ListView,您需要处理DrawColumnHeaderDrawItemDrawSubItem事件.

  • For drawing the ListView you need to handle DrawColumnHeader, DrawItem and DrawSubItem events.

DrawColumnHeader事件中绘制复选框.

代码:

private void listView1_DrawColumnHeader(object sender, 
                                        DrawListViewColumnHeaderEventArgs e)
{
    if (e.ColumnIndex == 0)
    {
        e.DrawBackground();
        bool value = false;
        try
        {
            value = Convert.ToBoolean(e.Header.Tag);
        }
        catch (Exception)
        {
        }
        CheckBoxRenderer.DrawCheckBox(e.Graphics, 
            new Point(e.Bounds.Left + 4, e.Bounds.Top + 4),
            value ? System.Windows.Forms.VisualStyles.CheckBoxState.CheckedNormal :
            System.Windows.Forms.VisualStyles.CheckBoxState.UncheckedNormal);
    }
    else
    {
        e.DrawDefault = true;
    }
}

private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)
{
    e.DrawDefault = true;
}

private void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
    e.DrawDefault = true;
}

private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
{
    if (e.Column == 0)
    {
        bool value = false;
        try
        {
            value = Convert.ToBoolean(this.listView1.Columns[e.Column].Tag);
        }
        catch (Exception)
        {
        }
        this.listView1.Columns[e.Column].Tag = !value;
        foreach (ListViewItem item in this.listView1.Items)
            item.Checked = !value;

        this.listView1.Invalidate();
    }
}

截屏:

  • 在上图中,我有3列.
  • 我为第一列设置了空文本.
  • 我将ListViewCheckBoxes属性设置为true.
  • 我为项目设置了空文本,并为每个项目添加了2个子项目.
  • In the above image I have 3 columns.
  • I set empty text for first column.
  • I Set CheckBoxes property of ListView to true.
  • I Set empty text for items and added 2 sub items for each item.

这篇关于如何在c#Winform App中将复选框添加到列表视图列标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆