I have an application written in wpf that loads some web pages, parses the html code and saves some values.
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; }
This is the object model that I use. This is a simplified version, and I do not want you to reorganize it, there is a reason why I wrote it this way. In ListOfItems class is a method that performs the entire task (other methods are read to read the code) - loads the source, parses and populates the ListToBind data, fe
[0] => NameOfItem = "FirstOne", Properties = {99, #FF00FF00} [1] => NameOfItem = "SecondOne", Properties = {50, #FFFF0000} etc.
As you can see, when this DownloadItems method completes its task, the OnDownloadCompleted event is OnDownloadCompleted . In the main thread, the following code
void listOfItems_OnDownloadCompleted(object sender, EventArgs args) { dataGrid.Dispatcher.Invoke(new Action(() => { dataGrid.ItemsSource = ListOfItemsInstance.ListToBind; })); }
The DataGrid on MainWindow.xaml populated with values ββdue to the following xaml code snippet.
<DataGrid Name="dataGrid" AutoGenerateColumns="False"> <DataGrid.Columns> <DataGridTextColumn Header="Tag" Binding="{Binding Name}"/> <DataGridTextColumn Header="Color" Binding="{Binding MyClass.Percentage}"> </DataGridTextColumn> </DataGrid.Columns> </DataGrid>
It works great. But there is this problem. Try uncommenting the xaml comment and you get the Must create DependencySource on same Thread as the DependencyObject. error Must create DependencySource on same Thread as the DependencyObject. .
Finally, my question is: how to avoid this error?
EDIT:
In the end, it should look like this. This image is taken from MS Excel and painted in Adobe Photoshop.
