Cobret
Cobret

Reputation: 34

C# UWP Create UI content in another thread

Can I create UI content with async methods? I was trying to extract data from files and visualize them in the async void. But I caught this error

The application called an interface that was marshalled for a different thread

I want to create multiple items in another thread and show progressBar while it is running. How should I do it?

UPDATE

I am trying to create collection of items and put them like children to StackPanel:

SomeViewModel.cs - class of home page

ObservableCollection<NoteRepresentation> result = new ObservableCollection<NoteRepresentation>();
        
await Task.Run(() => 
 { 
    foreach (var item in DataTransit.Notes) result.Add(new NoteRepresentation(item));
 }

NoteRepresentation.cs - userControl class

public NoteRepresentation(Note note)
{
    //some code
    this.DataContext = this;
    this.InitializeComponent();
}

Upvotes: 0

Views: 198

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456457

I want to create multiple [UI] items in another thread and show progressBar while it is running. How should I do it?

This is not possible.

It is possible to load the data for those UI controls in another thread, or to do it asynchronously. But it is not possible to create the UI controls themselves on another thread.

Normally, this is not a problem, since you should not be creating thousands of UI controls to display to the user anyway - no user could reasonably interact with thousands of UI controls. If you find yourself in this situation, you'll need to use data virtualization, which is a way of pretending to create the UI controls but in reality they're only created as needed (e.g., when the user scrolls).

Alternatively, you can rethink the UI design completely. Is it really useful for the user to be able to scroll through all these values? Would a paging design be better? If there are really thousands of these, perhaps a filter is necessary?

Upvotes: 2

Related Questions