问题
I fill a TreeView (WPF) in the code and want to use some icons in the items. I can load and add BitmapImage but it is only displayed, when the BitmapImage is also assigned to another ImageControl in the window (and shown there):
TreeViewItem newItem = new TreeViewItem();
Image tempImage = new Image();
BitmapImage bitmapImage = new BitmapImage(new Uri(@"/Resources/ok-01.png", UriKind.Relative));
tempImage.Source = bitmapImage;
imageControlInWindow.Source = bitmapImage; //if I delete this line (it is not needed) the image in the TreeViewItem is not shown
TextBlock tempTextBlock = new TextBlock();
tempTextBlock.Inlines.Add(tempImage);
tempTextBlock.Inlines.Add("SomeText");
newItem.Header = tempTextBlock;
How can I force the image to be shown in the TreeView without the hack of showing it outside the treeview as copy?
回答1:
You are not loading the image files from a proper Resource File Pack URI.
It should look like this:
var bitmapImage = new BitmapImage(new Uri("pack://application:,,,/Resources/ok-01.png"));
The Build Action of the image file must be set to Resource.
回答2:
MainWindow:
<Window x:Class="TreeViewTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TreeView ItemsSource="{Binding Items}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate >
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Text}" />
<Image Source="{Binding ImageSource}" Stretch="Uniform" Height="30"/>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
Code behind:
public partial class MainWindow
{
public List<MyItem> Items { get; private set; }
public MainWindow()
{
InitializeComponent();
DataContext = this;
Items = new List<MyItem>
{
new MyItem {Text = "Item 1", ImageSource = "/image1.png"},
new MyItem {Text = "Item 2", ImageSource = "/image2.png"}
};
}
}
public class MyItem
{
public string Text { get; set; }
public string ImageSource { get; set; }
}
来源:https://stackoverflow.com/questions/33118632/how-to-add-and-show-images-in-a-wpf-treeview