Skip to main content
 首页 » 编程设计

c#之绑定(bind)后台时"Must create DependencySource on same Thread as the DependencyObject."

2024年02月06日39cmt

我想更改 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> 

在后面的代码中,我有一个 BackGround 和 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); 
    } 
} 

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

Must create DependencySource on same Thread as the DependencyObject

异常。你能告诉我如何解决吗?谢谢。

请您参考如下方法:

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

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