C# 当ListView作为活动对象时,将标签文本更改为写入内容

C# 当ListView作为活动对象时,将标签文本更改为写入内容,c#,forms,listview,keydown,C#,Forms,Listview,Keydown,当我点击我的列表视图并写下“此文本!”时,我希望我的标签(或者文本框,如果更容易的话)将文本更改为“此文本!” 如何执行此操作?您可以使用AfterLabelEdit事件: private void listView1_AfterLabelEdit(object sender, LabelEditEventArgs e) { yourLabel.Text = e.Label; } 别忘了把活动联系起来 如果要在键入时显示新文本,可以尝试在BeforeLabelEdit和AfterLa

当我点击我的列表视图并写下“此文本!”时,我希望我的标签(或者文本框,如果更容易的话)将文本更改为“此文本!”


如何执行此操作?

您可以使用
AfterLabelEdit
事件:

private void listView1_AfterLabelEdit(object sender, LabelEditEventArgs e)
{
     yourLabel.Text = e.Label;
}
别忘了把活动联系起来

如果要在键入时显示新文本,可以尝试在BeforeLabelEdit和AfterLabelEdit事件之间收听键盘,也可以覆盖自己的文本框并使用其TextChanged事件

我认为这是容易的,但如果你想做一些特殊的事情,如不允许编辑键等,这将永远意味着一些额外的工作

下面是一个如何在项目上覆盖文本框的简短示例:

TextBox EditCell = new TextBox();

public Form1()
{
    InitializeComponent();
    //..
    EditCell.TextChanged += EditCell_TextChanged;
    EditCell.Leave += EditCell_Leave;
    EditCell.KeyDown += EditCell_KeyDown;
}

void EditCell_TextChanged(object sender, EventArgs e)
{
    yourLabel.Text = EditCell.Text;
}

void EditCell_Leave(object sender, EventArgs e)
{
    ListViewItem lvi = EditCell.Tag as ListViewItem;
    if (lvi != null)   lvi.Text = EditCell.Text;
    EditCell.Hide();
}

void EditCell_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter) 
    { 
        e.Handled = true; 
        EditCell_Leave(null, null);
    }
    else if (e.KeyCode == Keys.Escape)
    {
        e.Handled = true;
        EditCell.Tag = null;
        EditCell_Leave(null, null);
    }
    e.Handled = false;
}


private void listView1_BeforeLabelEdit(object sender, LabelEditEventArgs e)
{
    // stop editing the item!
    e.CancelEdit = true;
    ListViewItem lvi = listView1.Items[e.Item];
    EditCell.Parent = listView1;
    EditCell.Tag = lvi;
    EditCell.Bounds = lvi.Bounds;
    EditCell.BackColor = Color.WhiteSmoke;  // suit your taste!
    EditCell.Text = lvi.Text;
    EditCell.Show();
    EditCell.SelectionStart = 0;
    EditCell.Focus();
    EditCell.Multiline = true;  // needed to allow enter key
}
上面的代码工作正常,但由于我们的聊天已经确定,您实际上只想抓取键盘输入并将其指向
标签
,下面是一个非常简单的解决“隐藏”问题的方法:

首先,将您的
表单
KeyPreview
设置为
true
。然后连接
表单的
按键事件

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (ActiveControl == listView1)
    {
        e.Handled = true; // needed to prevent an error beep
        yourLabel.Text += e.KeyChar.ToString();
    }

}
这将不允许任何编辑,只允许标签文本增长。如果您愿意,您可能需要扩展一些附加功能,如为
Backspace
编码

  if (e.KeyChar == (char)Keys.Back && yourLabel.Text.Length > 0) 
      yourLabel.Text = yourLabel.Text.Substring(0, yourLabel.Text.Length - 1);
  else yourLabel.Text += e.KeyChar.ToString();

我为ListView做了一个AfterLabeleEdit,并像你的例子一样将代码放在里面,但是当我键入时什么都没有发生。你是说当你按enter键或离开该项时什么都没有发生?应该的!还是说打字的时候?顾名思义,该事件在编辑完成后触发。不支持AFAIK在键入时更新标签。键入时不会发生任何事情,这正是我想要的。这将非常困难。如果你拿不到覆盖的文本框,你必须在所有键到达它之前听它们,这意味着你不仅要理解输入,还要理解编辑、导航和剪贴板键。很难。用你自己的文本框来伪造它要简单得多,你可以编辑..很好。但是我忘了告诉你导航不应该工作。我的意思是,应该禁用左、右、删除、退格、剪贴板相关等等。只有键入的字符才应放入标签中。所以我认为“听所有的关键点”是解决这个问题的方法。