如何重命名列表框中的项目?

How to rename an item in a ListBox?

我希望用户能够直接重命名 ListBox 中的项目,其效果与我们在 Windows 的文件资源管理器中看到的效果相同。像这样:

有没有简单的方法可以做到这一点?

感谢您的回答。

假设您的项目 class 有一个 read/write 属性 显示在列表框中,例如

public class MyItem
{
    public string ItemText { get; set; }
}

您可以将列表框的 ItemTemplate 中文本框的文本 属性 绑定到 属性:

<ListBox x:Name="ListBox">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBox Text="{Binding ItemText}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

为了在您向 TextBox 中键入内容时更新 ItemText 属性(与 TextBox 失去焦点时相反),您必须设置 Binding 的 UpdateSourceTrigger:

<TextBox Text="{Binding ItemText, UpdateSourceTrigger=PropertyChanged}"/>