聽起來你需要在你的圖片上撥打.Freeze()
。
雖然,我也有類似的情況在我的應用程序,這是我如何做它(不使用.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#代碼:
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)));
}
我在哪裏創建我的節點(作爲示例):
TreeViewItem item = new TreeViewItem();
item.DataContext = this.typeIcons["harddrive"];