如何在 WPF TreeView 中添加和显示图像?

How to add and show images in a WPF TreeView?

我在代码中填充了一个TreeView (WPF),想在项目中使用一些图标。 我可以加载和添加 BitmapImage 但它只显示,当 BitmapImage 也被分配给 window 中的另一个 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;

如何强制图像在 TreeView 中显示,而不会将其作为副本显示在 TreeView 之外?

主窗口:

<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>

后面的代码:

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; }
}

您没有从正确的 Resource File Pack URI.

加载图像文件

它应该是这样的:

var bitmapImage = new BitmapImage(new Uri("pack://application:,,,/Resources/ok-01.png"));

镜像文件的Build Action必须设置为Resource