This is the working code(but on 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 make 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 a ConentControl
and place it in the Grid, which is inside a listview
with multiple ContentControls
.) The shown solution is crashing because a different thread owns the MainGrid
.
Anyone got good ideas for this? (would love to do it on another thread because the ContentControl
is heavy, like 3 sec to create the layout. It's a generic view which creates itself according to parameters.)
EDIT:
The main problem is that during creation of these views, my whole application hangs. Which is very unwanted. My goal is to move this workload to another (or multiple) other thread(s).
You can force the binding to be performed on a different thread by using the
IsAsync
property.This will perform the binding to
Work
on a new thread and the content will be populated when it's done. You won't need to bother with your code-behind stuff.You can find a nice tutorial of it in action here.