【问题标题】:Edit ListView Group Headers like we can edit ListViewItems编辑 ListView 组标题,就像我们可以编辑 ListViewItems
【发布时间】:2015-05-02 08:08:51
【问题描述】:

在 WinForms 应用程序中,我们可以通过单击两次来重命名 ListView 项。我们可以以同样的方式重命名组标题吗?有没有办法启用它?

【问题讨论】:

  • 有点牵强,但毕竟可行!

标签: c# .net winforms listview


【解决方案1】:

我想这毕竟是可行的,尽管不是通过简单地启用一个属性..

注意:下面的代码假设ListView处于Details模式!

从空空间中分辨出Group 的技巧是测试ListView 的右侧。另一个技巧是稍等片刻:单击将选择 Group Items。只有在那之后我们才能继续..

这是一个用TextBox 覆盖Group 的示例:

// class variable to test if have been hit twice in a row
ListViewGroup lastHitGroup = null;

private void listView1_MouseDown(object sender, MouseEventArgs e)
{
    // check left side to see if we are at the empty space
    ListViewItem lvi = listView1.GetItemAt(4, e.Y);
    // yes, no action! reset  group
    if (lvi != null)  { lastHitGroup = null; return; }
    // get the height of an Item
    int ih = listView1.GetItemRect(0).Height;
    // to get the group we need to check the next item:
    ListViewItem lviNext = listView1.GetItemAt(4, e.Y + ih);
    // no next item, maybe the group is emtpy, no action
    if (lviNext == null) return;
    // this is our group
    ListViewGroup editedGroup = lviNext.Group;
    // is this the 2nd time?
    if (lastHitGroup != editedGroup) {lastHitGroup = editedGroup; return;}
    // we overlay a TextBox
    TextBox tb = new TextBox();
    tb.Parent = listView1;
    // set width as you like!
    tb.Height = ih;
    // we position it over the group header and show it
    tb.Location = new Point(0, lviNext.Position.Y - ih - 4);
    tb.Show();
    // we need two events to quit editing
    tb.KeyPress += (ss, ee) =>
    {
        if (ee.KeyChar == (char)13)  // success
        {
            if (editedGroup != null && tb.Text.Length > 0)
                editedGroup.Header = tb.Text;
            tb.Hide();
            ee.Handled = true;
        }
        else if (ee.KeyChar == (char)27)  // abort
        {
            tb.Text = ""; tb.Hide(); ee.Handled = true;
        }

    };
    tb.LostFocus += (ss, ee) =>  // more success
    {
       if (editedGroup != null && tb.Text.Length > 0)
          editedGroup.Header = tb.Text;
       tb.Hide();
    };
    // we need to wait a little until the group items have been selected
    Timer lvTimer = new Timer();
    lvTimer.Interval = 333;  // could take longer for a huge number of items!
    lvTimer.Tick += (ss,ee) => { tb.Focus(); lvTimer.Stop();};
    lvTimer.Start();

}

【讨论】:

    猜你喜欢
    • 2020-10-25
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多