Search code examples
c#wpflistboxlistboxitem

How to rename an item in a ListBox?


I want the user to be able to directly rename an item in a ListBox with the same effect as we can see in the file explorer of Windows by example. Like this:

enter image description here

Is there a simple way to achieve this?

Thanks for your answers.


Solution

  • Assuming your item class has a read/write property that is displayed in the ListBox, e.g.

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

    you could bind the Text property of a TextBox in the ItemTemplate of the ListBox to that property:

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

    In order to have the ItemText property updated while you type into the TextBox (in contrast to when the TextBox loses focus), you would have to set the Binding's UpdateSourceTrigger:

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