gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:51:16 62 4
gpt4 key购买 nike

我有一个用 wpf 编写的应用程序,它下载一些网页,解析 html 代码并保存一些值。

class ListOfItems
{
public List<SomeObject> ListToBind;
public void DownloadItems()
{
Task.Factory.StartNew(() =>
{
...
...
if (OnDownloadCompleted != null)
OnDownloadCompleted(this, EventArgs.Empty);
}
}
}

class SomeObject
{
public string NameOfItem;
public MyClass Properties;
}

class MyClass
{
public int Percentage;
public SolidColorBrush Color;
}

这是我正在使用的对象模型。是简化版的,不想让你重组,我这样写是有原因的。在 ListOfItems 类中是完成所有工作的方法(内部使用了一些其他方法使代码可读)- 下载源代码,解析并用数据填充 ListToBind,f.e.

[0] => NameOfItem = "FirstOne", Properties = {99, #FF00FF00}
[1] => NameOfItem = "SecondOne", Properties = {50, #FFFF0000}
etc.

如您所见,当此方法 DownloadItems 完成其工作时,将引发 OnDownloadCompleted 事件。在主线程中是以下代码

void listOfItems_OnDownloadCompleted(object sender, EventArgs args)
{
dataGrid.Dispatcher.Invoke(new Action(() => {
dataGrid.ItemsSource = ListOfItemsInstance.ListToBind;
}));
}

由于以下 xaml 代码片段,MainWindow.xaml 上的 DataGrid 填充了值。

<DataGrid Name="dataGrid" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Tag" Binding="{Binding Name}"/>
<DataGridTextColumn Header="Color" Binding="{Binding MyClass.Percentage}">
<!--<DataGridTextColumn.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="Background" Value="{Binding MyClass.Color}" />
</Style>
</DataGridTextColumn.CellStyle>-->
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>

它工作得很好。但是有这个问题。尝试取消注释已注释的 xaml 片段,您将得到 Must create DependencySource on same Thread as the DependencyObject. 错误。

最后,我的问题是,如何避免这个错误?

编辑:

最后应该是这样的。此图片取自 MS Excel,并在 Adob​​e Photoshop 中上色。

example

最佳答案

SolidColorBrushFreezable这是派生的 DispatcherObject。 DispatcherObjects 具有线程关联性——即它只能在创建它的线程上使用/交互。然而,Freezables 确实提供了卡住实例的能力。这将防止对该对象进行任何进一步的更改,但它也会释放线程关联。因此,您可以更改它,以便您的属性不存储像 SolidColorBrush 这样的 DependencyObject,而只存储 Color。或者您可以使用 Freeze 卡住您正在创建的 SolidColorBrush方法。

关于c# - 必须在与 DependencyObject 相同的线程上创建 DependencySource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7865514/

62 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com