简体   繁体   中英

Update Text of ListBoxItem WPF

In my project, when the user clicks the "Save Changes" button it fires an event which updates the name of the person that they are editing. I've been able to successfully implement this code in windows forms:

listBoxNames.SelectedItems[0].Text = forenameTxtBox.Text + " " +
                                      surnameTxtBox.Text;

But in WPF, listBoxNames.SelectedItems[0] doesn't have a property of 'text'.

Is there any way around this so that I can edit the text of the ListBoxItem in turn updating the ListBox with the new name? Or would I have to an ObservableCollection<string> ?

Typecast selectedItem to actual object instance and edit its property instead.

Assuming class is Person with Name property in it. It will be like this:

((Person)listBoxNames.SelectedItems[0]).Name = forenameTxtBox.Text + " " + 
                                                surnameTxtBox.Text;

Also in case you want to update UI on any property change, Person class should implement INotifyPropertyChanged . Read this article how to implement INPC on class .


Assuming you are simply binding to list of strings, you can update it like this:

listBoxNames.Items[listBoxNames.SelectedIndex] = forenameTxtBox.Text + " " + 
                                                    surnameTxtBox.Text;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM