I have made an application with a Tree
and a TreeView
where the user can add and remove
nodes on the fly.
I am using three different icons in the tree to mark various things by using the ordinary way of creating a StackPanel (in code not in XAML).
As it is now I have to load these icons for each of the nodes I add from the file system which consumes a lot of resources and memory because I can not find a way of "reusing" the icons between the nodes in the tree.
I tried to create three default images at start but I could only use them for three nodes, the fourth node complain and said that the item (the image) was already in use.
I have seen on the internet some possibilities of creating a ImageList but those seems to be 开发者_开发百科TreeViewitem
related which mean that I have to create a new ImageList
for each node?
Or can the same ImageList
be reused between all nodes?
Sounds to me that you need to call .Freeze()
on your images.
Although, I have a similar case in my app and this is how I have done it (without using .Freeze()
):
XAML:
<TreeView Name="treeViewFolders" SelectedItemChanged="treeViewFolders_SelectedItemChanged" TreeViewItem.Expanded="treeViewFolders_Expanded" Margin="0,4,0,6">
<TreeView.Resources>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="0,2">
<Image x:Name="img" Stretch="None" RenderOptions.BitmapScalingMode="NearestNeighbor"
Source="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=TreeViewItem}, Path=DataContext}"/>
<TextBlock Text="{Binding}" Margin="5,0,10,0" />
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</TreeView.Resources>
</TreeView>
c# code:
private readonly System.Collections.Generic.Dictionary<string, ImageSource> typeIcons = new Dictionary<string, ImageSource>();
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.typeIcons.Add("winhdd", new BitmapImage(new Uri("Images/Icons/winhdd.png", UriKind.Relative)));
this.typeIcons.Add("harddrive", new BitmapImage(new Uri("Images/Icons/hdd.png", UriKind.Relative)));
this.typeIcons.Add("removable", new BitmapImage(new Uri("Images/Icons/removablehdd.png", UriKind.Relative)));
this.typeIcons.Add("folder", new BitmapImage(new Uri("Images/Icons/folder.png", UriKind.Relative)));
}
Where I'm creating my nodes (as an example):
TreeViewItem item = new TreeViewItem();
item.DataContext = this.typeIcons["harddrive"];
精彩评论