I’m beginner in programming in C# and WPF and I’m creating a file manager with 2 ListViews, all items bounded. In ListView there are some GridViewColumns and first has CellTemplate because I want there icon of file/folder and its name. The CellTemplate is:
<DataTemplate x:Key="IconTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Image Source="{Binding Path=itemIcon}" Width="20" Grid.Column="0"/>
<TextBlock Grid.Column="1" Text="{Binding Path=itemName}" />
</Grid>
</DataTemplate>
And I had one Class : ObservableCollection where all directories and files are added to the collection and for every file its icon is converted from file. MyItem class contains few strings for name, extension etc. and one ImageSource for those icons. All worked well till i realised that some folders with different files freezes the program because of converting those icons. So now i bind some general icon for every file and then i want to convert and change it in another thread. So in main class i created global ObservableCollection for items and because i don’t know how to load them from the listView back i have moved the filling Collection function from Observable-class to the main class. Now I’m able to change items in listview from new thread but – finally here comes my problem – i get XamlParseException – Must create DependencySource on same Thread as the DependencyObject. When i tried to change file’s name (string) it worked perfectly (so far I’m testing it only on button click)! I tried to implement dependencyObject to MyItem class according to some reference i found on the internet but it didn’t worked. This changing icon function.
for (int i = leftDirectories.Length; i < (leftDirectories.Length + leftFiles.Length); i++)
{
FileToImageIconConverter some = new FileToImageIconConverter(locationLeft + leftFiles[i - leftDirectories.Length].Name);
ImageSource imgSource = some.Icon;
leftFilesLoad[i].itemIcon = imgSource;
this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
{
contentLeft.Items.Refresh();
}
);
Quite long article, stackoverflow says be specific :-D. Thank so much for everyone trying help me. I’m looking forward to your replies and I’m ready to show you all code you’ll need.
The exception is occurring because you are creating the
ImageSourceon the none-UI thread. Unless you freeze the object, you cannot do this. You’re going to want all the UI related logic to included in yourBeginInvokecall. Try this insteadThat should keep all UI related activity on the UI thread.