I want to create a Grid
element on a different thread (creating the whole Grid is expensive) and update a StackPanel
via Dispatcher
. But calling Dispatcher
always throws an InvalidOperationException
, no matter what I do.
Here is my code:
Grid grid = new Grid();
Dispatcher.Invoke(() => stackPanel.Children.Add(grid));
What I've tried:
Closing over a variable [didn't work]
Grid grid = new Grid(); Grid closedOverGrid = grid; Dispatcher.Invoke(new Action(() => stackPanel.Children.Add(closedOverGrid)));
Using BeginInvoke [didn't work]
//declaring this in another thread. Grid grid = new Grid(); AddToPanel(grid); private void AddToPanel(Grid grid) { Dispatcher.BeginInvoke((Action)(() => { stackPanel.Children.Add(grid); })); }
Using a full declaration with DispatcherPriority [didn't work]
Grid grid = new Grid(); System.Windows.Application.Current.Dispatcher.BeginInvoke( DispatcherPriority.Background, new Action(() => stackPanel.Children.Add(grid)));
Tried the .Freeze() method [didn't work]
Grid grid = new Grid(); grid.Freeze(); // Not possible.
Is it really not possible, or am I missing something? Thank you for your answers/comments.