我在资源文件的Style
TreeViewItems
中有以下代码:
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Name="img"
Width="20"
Height="20"
Stretch="Fill"
Source=""/>
<TextBlock Text="{Binding}" Margin="5,0" />
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
我现在如何在代码中设置TreeViewItem
的图像/来源?
答案 0 :(得分:0)
XAML:
<Window x:Class="TreeViewWpfApplication.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 Name="treeView">
</TreeView>
</Grid>
</Window>
代码背后:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
CreateTree();
}
private void CreateTree()
{
treeView.Items.Add(GetTreeView("text"));
}
private TreeViewItem GetTreeView(string text)
{
TreeViewItem newTreeViewItem = new TreeViewItem();
// create stack panel
StackPanel stack = new StackPanel();
stack.Orientation = Orientation.Horizontal;
// create Image
Image image = new Image();
image.Source = new BitmapImage(new Uri(@"/Images/YourImage.png", UriKind.Relative));
// Label
TextBlock lbl = new TextBlock();
lbl.Text = text;
lbl.TextWrapping = TextWrapping.Wrap;
lbl.Width = 139;
// Add into stack
stack.Children.Add(image);
stack.Children.Add(lbl);
// assign stack to header
newTreeViewItem.Header = stack;
return newTreeViewItem;
}
}
}
注意image.Source = new BitmapImage(new Uri(@"/Images/YourImage.png", UriKind.Relative))
其中&#34; / Images /&#34; - 文件夹名称。