我在代码中填写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中而不会将其作为副本显示在树视图之外?
答案 0 :(得分:2)
您没有从正确的Resource File Pack URI加载图像文件。
它应该是这样的:
var bitmapImage = new BitmapImage(new Uri("pack://application:,,,/Resources/ok-01.png"));
图像文件的构建操作必须设置为资源。
答案 1 :(得分:1)
主窗口:
<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; }
}