C
C#2mo ago
Pludam

✅ [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.
No description
6 Replies
Pludam
PludamOP2mo ago
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
canton7
canton72mo ago
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?
Honza K.
Honza K.2mo ago
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?
canton7
canton72mo ago
(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
Pludam
PludamOP2mo ago
@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!
canton7
canton72mo ago
Cool! As I say, do make sure that you only add/remove items to it from the UI thread

Did you find this page helpful?