gpt4 book ai didi

c# - 像编辑 ListViewItems 一样编辑 ListView Group Headers

转载 作者:太空宇宙 更新时间:2023-11-03 13:08:28 25 4
gpt4 key购买 nike

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

最佳答案

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

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

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

下面是一个用 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();

}

关于c# - 像编辑 ListViewItems 一样编辑 ListView Group Headers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29999930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com