“必须在与 DependencyObject 相同的线程上创建 DependencySource。” 绑定背景时

jas*_*son 1 c# wpf multithreading backgroundworker

我想更改 Backgroundworker 中数据网格的标签和背景。我有这样的网格:

<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>
Run Code Online (Sandbox Code Playgroud)

在后面的代码中,我有 aBackGround 和 aPace,如下所示:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以正确地看到 aPace 的结果,但一秒钟后我得到

必须在与 DependencyObject 相同的线程上创建 DependencySource

例外。你能告诉我如何解决吗?谢谢。

Mik*_*chs 5

无论代码直接访问您的 UI,您都只能在 UI 线程上运行。使用调度程序在那里运行它,例如:

Application.Current.Dispatcher.Invoke(() =>
{
    // the code that's accessing UI properties
});
Run Code Online (Sandbox Code Playgroud)