【问题标题】:How to add and show images in a WPF TreeView?如何在 WPF TreeView 中添加和显示图像?
【发布时间】:2015-10-14 06:59:33
【问题描述】:

我在代码中填写了一个 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 之外?

【问题讨论】:

  • 为什么不为树视图项目建立数据模板?
  • InvalidateVisual怎么样
  • 图像文件的构建操作应设置为资源。然后它将由 Resource File Pack URI: new Uri("pack://application:,,,/Resources/ok-01.png") 加载。
  • 感谢 Clemens ... 成功了 :-) 想要将此添加为正确答案吗?非常感谢! :-)

标签: c# wpf image treeview bitmapimage


【解决方案1】:

您没有从正确的Resource File Pack URI 加载图像文件。

应该是这样的:

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

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

【讨论】:

    【解决方案2】:

    主窗口:

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

    【讨论】:

    • 肯定在树视图中图像通常属于树项的左侧?在文本之后有一个非常丑陋的 UI。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-12
    • 1970-01-01
    相关资源
    最近更新 更多