TextBox c# 引用字符串

TextBox c# refer string

是否可以在 c# 中引用字符串作为 TextBox 的内容?我有一个列表框,里面有一堆对象。每个对象都包含一个字符串。当我 select 列表框中的一个对象时,我希望它的字符串成为 TextBox 中的内容,这样我写的任何内容都会保存到字符串中。

例如在 Java 中,您可以在一个对象中有一个 PlainDocument,并且每当您在 JList 中 select 一个不同的对象时,您可以将 JTextField 中的文档设置为对象 PlainDocument。

可以使用

访问文本框的内容
myTextBox.Text

这个 属性 需要字符串,所以你的答案是肯定的。我想简单地分配这个 属性 就可以了。

更新

我认为您需要这样的东西(假设您使用的是 WinForms):

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if(listBox1.SelectedItem != null)
            textBox1.Text = listBox1.SelectedItem.ToString();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        int index = listBox1.Items.IndexOf(listBox1.SelectedItem);
        listBox1.Items.Remove(listBox1.SelectedItem);
        listBox1.Items.Insert(index, textBox1.Text);            
    }

虽然在 WinForms 中有一个针对文本框的 TextChanged 事件的操作,但是从那里更改列表框有点棘手(最终会无限地相互调用),因为我们已经从列表框的更改事件更改文本框。

添加一个按钮来执行此操作会大大简化它。

您可以在事件处理程序中使用 Data Binding for an automated solution or you can manually listen for SelectedIndexChanged event of the list box and set the Text 属性。

listBox1.SelectedIndexChanged += (o, e) => {
   object selectedItem = listBox1.SelectedItem;
   textBox1.Text = selectedItem != null ? selectedItem.ToString() : null;
};