✅ [Avalonia] Problems Setting ItemSource of ListBox from Codebehind
I have networking running on an seperate Thread and i need to Display the Result of Server Discovery in a ListBox so the User can choose the server and Connect to it. for whatever reason setting the ItemSource Of the Listbox from the seperate Thread doesnt work when its implemented like its described here
How To Access the UI Thread | Avalonia Docs
This guide will show you how to access the UI thread in your Avalonia UI application.

6 Replies
The weird thing is Setting the Background Color of a Panel in the same Function where i try to set the ItemSource works
see the Picture
Looks like "Servers" is a list? Or an observable list?
(Either way, it's not going to be safe to read it from one thread while writing to it from another thread.)
You haven't said wht "doesn't work" actually means, but I'm going to guess it means that the UI doesn't update?
when the callback gets called and items source gets set, is the list populated with items? Are you accessing the same list instance (in any way) ever again?
why not just set one instance of observableCollection<> as the items source and add/populate this collection from received list instead?
(To add to that: if
Servers is a normal list, which you keep re-assigning, then: if ItemsSource has the value servers, and you assign that same servers object to it again, then nothing has changed and no UI is updated)
So either create a new list and assign that, or use an ObservableCollection
Do note that if you use an ObservableCollection you should only add and remove items from it on the UI thread, since it's not thread-safe
And if you take the approach of snapshotting Servers and sending the snapshot to the UI thread, then make sure you create the snapshot on the same thread that your server events are happening on@canton7 sorry for the late reply. Using ObservableCollection fixed it. wasnt using it before because i thought it needed the same setup as an Observable Property and i thought is was an mvvm only thing. Thanks for the Help!
Cool! As I say, do make sure that you only add/remove items to it from the UI thread