I have a TabConrol
that when a user does certain things, a new TabItem
is programmatically added. In this tab there is a Frame that will contain the desired Page.XAML
. This is all working perfectly like this;
private void addNewTab()
{
TabItem tab = new TabItem();
Grid g = new Grid();
Frame f = newFrame();
g.Children.Add(f);
tab.Content = g;
MyTabControl.Items.Add(tab);
MyTabControl.SelectedItem = tab;
}
private Frame newFrame()
{
Frame f = new Frame();
//Full logic for Frame removed
f.Navigate(new MyPage());
return f;
}
Issues is sometimes the loading of the new Frame
can take sometime. So I wanted to do this async. So while it loads there could be a loading animation. I figured that this would work;
private async void addNewTab()
{
TabItem tab = new TabItem();
Grid g = new Grid();
var test = Task<Frame>.Factory.StartNew(() => newFrame(selectTab, value));
await test;
f = test.Result;
g.Children.Add(f);
tab.Content = g;
MyTabControl.Items.Add(tab);
MyTabControl.SelectedItem = tab;
}
private Frame newFrame()
{
Frame f = new Frame();
//Full logic for Frame removed
f.Navigate(new MyPage());
return f;
}
Problem is that it returns the follow error on Frame f = new Frame();
in newFrame()
at run;
An exception of type 'System.InvalidOperationException' occurred in PresentationCore.dll but was not handled in user code
Additional information: The calling thread must be STA, because many UI components require this.
Starting to think I am trying to solve this the wrong way. What is the best way to handle this?