Create heavy ui element in another wpf thread
This is the working code (but on the UI thread):
<ContentControl
Width="{Binding Path=ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}}"
Focusable="True"
HorizontalAlignment="Right"
Content="{Binding Work}" >
</ContentControl>
This is the code I'm trying to do instead, but it doesn't work: (codebehind)
InitializeComponent();
var thread = new Thread(
() =>
{
var a = new ContentControl { Focusable = true, HorizontalAlignment = HorizontalAlignment.Right };
var binding = new Binding { Path = new PropertyPath("Work"), };
a.SetBinding(ContentProperty, binding);
MainGrid.Dispatcher.Invoke(new Action(() => { MainGrid.Children.Add(a); }));
}) { IsBackground = true };
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
My goal is to create ConentControl
and place it on a grid that is inside listview
with multiple ContentControls
.) The displayed solution fails because another thread belongs MainGrid
. Anyone have good ideas for this? (I would like to do this in a different thread, because it is ContentControl
heavy, for example, 3 seconds to create a layout. This is a general view that creates itself according to the parameters.)
EDIT:
The main problem is that my whole program freezes while creating these views. This is highly undesirable. My goal is to move this workload to another (or several) different thread (s).
source to share
You can force the binding on a different thread using the property IsAsync
.
Content="{Binding Work, IsAsync=True}"
This will bind to Work
in a new stream and the content will be filled when done. You don't need to worry about what you do with the code.
You can find a good tutorial on this in action here .
source to share