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

标签 c# wpf image treeview bitmapimage

我在代码中填充了一个 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;

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

最佳答案

您没有从适当的 Resource File Pack URI 加载图像文件.

它应该是这样的:

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

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

关于c# - 如何在 WPF TreeView 中添加和显示图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33118632/

相关文章:

c# - 将代码重构为 using 语句

c# - MVC View - 无法填充选择下拉列表中的列表

javascript - 上传前预览图像时出现意外行为

ios - Swift:如何在 iPad 的 LaunchScreen 上缩放图像

c# - Silverlight/.net 的条码阅读器组件、资源、推荐、动物之森?天啊

C# 列表到没有 Foreach 的字典 [错误]

c# - Wpf Dpi 和像素完美的 WriteableBitmap

c# - 不使用 WinForms 旋转光标

c# - WPF从DataTrigger更改图像

css - 使用 css 模糊背景图像