如何在 WPF TreeView 中添加和显示图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33118632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add and show images in a WPF TreeView?
提问by Konrad
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):
我在代码中填充了一个 TreeView (WPF),并希望在项目中使用一些图标。我可以加载和添加 BitmapImage 但它仅在 BitmapImage 也分配给窗口中的另一个 ImageControl 时显示(并显示在那里):
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?
如何强制将图像显示在 TreeView 中,而无需将其作为副本显示在 TreeView 之外?
回答by Clemens
You are not loading the image files from a proper Resource File Pack URI.
您没有从正确的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.
图像文件的 Build Action 必须设置为Resource。
回答by Ketobomb
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; }
}

