<TreeView Grid.Row="0" Grid.Column="0" x:Name="foldersItem" SelectedItemChanged="foldersItem_SelectedItemChanged"
Margin="5,5,15,5" Width="500" Background="#FFFFFFFF" BorderBrush="#FFFFFFFF" Foreground="#FFFFFFFF">
<TreeView.Resources>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Name="img" Width="20" Height="20" Stretch="Fill"
Source="{Binding
RelativeSource={RelativeSource
Mode=FindAncestor,
AncestorType={x:Type TreeViewItem}},
Path=Header,
Converter={x:Static local:HeaderToImageConverter.Instance}}" // 工具类:HeaderToImageConverter 方法:Convert
/>
<TextBlock Text="{Binding}" Margin="5,0" />
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</TreeView.Resources>
</TreeView>
#region HeaderToImageConverter
[ValueConversion(typeof(string), typeof(bool))]
public class HeaderToImageConverter : IValueConverter
{
public static HeaderToImageConverter Instance = new HeaderToImageConverter();
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if ((value as string).Equals(@"我的电脑"))
{
Uri uri = new Uri("pack://application:,,,/Images/windows.png");
BitmapImage source = new BitmapImage(uri);
return source;
}
else if ((value as string).Contains(@"\"))
{
Uri uri = new Uri("pack://application:,,,/Images/diskdrive.png");
BitmapImage source = new BitmapImage(uri);
return source;
}
else
{
Uri uri = new Uri("pack://application:,,,/Images/folder.png");
BitmapImage source = new BitmapImage(uri);
return source;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException("Cannot convert back");
}
}
#endregion // DoubleToIntegerConverter
标签:BitmapImage,object,Uri,uri,source,new,wpf,treeview,图标 From: https://www.cnblogs.com/xfn1688/p/17000993.html