Reputation: 7164
I want to change a label and background of a datagrid inside a Backgroundworker. I have Grid like this :
<Grid HorizontalAlignment="Center" Height="499" Margin="96,170,810,0" VerticalAlignment="Top" Width="486" Background="{Binding aBackGround}">
<Label Content="212" FontSize="100" HorizontalAlignment="Left" VerticalAlignment="Top" RenderTransformOrigin="-4.395,-11.154" Margin="173,22,0,0" Height="123" Width="178"/>
<Label Content="{Binding aPace}" FontSize="65" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="23,202,0,0" Height="84" Width="255"/>
</Grid>
In code behind I have aBackGround and aPace like this:
private Brush _aBackGround;
private string _apace;
public Brush aBackGround
{
get { return _aBackGround; }
set
{
_aBackGround= value;
RaisePropertyChanged(() => this.aBackGround);
}
}
public string aPace
{
get { return _apace; }
set
{
_apace = value;
RaisePropertyChanged(() => this.aPace);
}
}
I can see the result of aPace correctly but a second later I get
Must create DependencySource on same Thread as the DependencyObject
exception. Can you tell me how to fix it? Thanks.
Upvotes: 1
Views: 6075
Reputation: 12319
Whatever code is directly accessing your UI, you can only run on the UI thread. Use a dispatcher to run it there, e.g.:
Application.Current.Dispatcher.Invoke(() =>
{
// the code that's accessing UI properties
});
Upvotes: 10
Reputation: 187
Either move your value assignment to backgroundworker completed event
or
use invoke when you assign the value in the backgroundWorker do work
this.Invoke(new Action(() =>
{
this.aPace = "test";
}));
Upvotes: 1