我想要在列表框中重命名所选项目。 我该如何做到这一点? 谢谢。
编辑:数年后重新审视此问题;以下是根据您所使用的 UI 框架进行更改选定文本的方法。假设您想要更改所选文本。
ASP.Net WebForms
protected void ChangeListBoxSelectedItemText(string textToChangeTo)
{
lstBoxExample.SelectedItem.Text = textToChangeTo;
}
WPF - 假设ListBox包含Label对象
// To achieve this in WPF you have to cast the object
// This is because a ListBox can contain numerous types of UI objects
var selectedLabel = (Label)lstBoxExample.SelectedItem;
selectedLabel.Content = "Text to change to";
WinForms
// There may very well be a better way to do this
lstBoxExample.Items[lstBoxExample.SelectedIndex] = "New Item";
ListBox
包含对象。你所说的“重命名”一个项目是什么意思?
如果你想改变列表中显示的文本,你需要更改对象,使其 ToString
方法返回所需的文本。
通常情况下,你可能会在 ListBox
中存储字符串,在这种情况下,为了“重命名”一个项目,你需要删除旧项目并在相同的索引中插入新文本。
ListBox.SelectedItem
的类型是Object
。上次我检查时,System.Object
没有 Text 成员。这对于System.Windows.Forms.ListBox
(WinForms)和System.Windows.Controls.ListBox
(WPF)都是正确的。 - Tergiver