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

Change Label text to what is written, when ListView as active object

当我点击我的 ListView 并写入 "this text!" 时,我想要我的 Label(或 TextBox 如果这样更容易)将文本更改为 "this text!".

我该怎么做?

您可以使用 AfterLabelEdit 事件:

private void listView1_AfterLabelEdit(object sender, LabelEditEventArgs e)
{
     yourLabel.Text = e.Label;
}

别忘了勾搭活动!

如果您想在键入时显示新文本,您可以尝试在 BeforeLabelEdit 和 AfterLabelEdit 事件之间收听键盘,或者您可以覆盖您自己的 TextBox 并使用其 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
}

上面的代码工作正常,但由于我们的聊天已经确定您实际上只想获取键盘输入并将其定向到 Label,这里是 [=38= 的更简单的解决方案] 问题..:[=​​22=]

首先将 FormsKeyPreview 设置为 true。然后挂接FormKeyPressed事件:

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();