Ond*_*cek 8 c# wpf datagrid multithreading dependency-properties
我有一个用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;
}
Run Code Online (Sandbox Code Playgroud)
这是我正在使用的对象模型.它是简化版本,我不希望你重新组织它,我有这样写道的原因.在ListOfItems
类中是执行所有工作的方法(内部使用一些其他方法使代码可读) - 下载源,解析和填充ListToBind
数据,fe
[0] => NameOfItem = "FirstOne", Properties = {99, #FF00FF00}
[1] => NameOfItem = "SecondOne", Properties = {50, #FFFF0000}
etc.
Run Code Online (Sandbox Code Playgroud)
如您所见,当此方法DownloadItems
完成其作业时,OnDownloadCompleted
将引发事件.在主线程中是以下代码
void listOfItems_OnDownloadCompleted(object sender, EventArgs args)
{
dataGrid.Dispatcher.Invoke(new Action(() => {
dataGrid.ItemsSource = ListOfItemsInstance.ListToBind;
}));
}
Run Code Online (Sandbox Code Playgroud)
MainWindow.xaml
由于以下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>
Run Code Online (Sandbox Code Playgroud)
它工作得很好.但是存在这个问题.尝试取消注释已注释的xaml片段,您将收到Must create DependencySource on same Thread as the DependencyObject.
错误消息.
最后,我的问题是,如何避免这个错误?
编辑:
它最终应该看起来像这样.此图片来自MS Excel并在Adobe Photoshop中着色.
小智 24
所述的SolidColorBrush是一个可冻结其是衍生DispatcherObject的.DispatcherObjects具有线程关联性 - 即它只能在创建它的线程上使用/交互.然而,Freezables提供了冻结实例的能力.这将阻止对对象的任何进一步更改,但它也将释放线程关联.因此,您可以更改它,以便您的属性不存储像SolidColorBrush这样的DependencyObject,而只是存储Color.或者,您可以使用冻结方法冻结正在创建的SolidColorBrush .