Reputation: 383
I'm trying to make a treeview with items that has both image and text.
I have followed this example http://www.codeproject.com/Articles/124644/Basic-Understanding-of-Tree-View-in-WPF but I'm getting a strange behavior on the treeviewitem header.
The header is supposed to contain an image and a label but instead this is shown as the header text of all treeviewitems: System.Windows.Controls.StackPanel
Here is my code:
tree_view.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(@"/ComponentName;component/Resources/Images/warning.png", UriKind.Relative));
// Label
Label lbl = new Label();
lbl.Content = text;
// Add into stack
stack.Children.Add(image);
stack.Children.Add(lbl);
// assign stack to header
newTreeViewItem.Header = stack;
return newTreeViewItem;
}
Edit:
Also, I have this in the TreeView's HeaderTemplate to wrap the text:
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate>
<TextBlock Width="139" TextWrapping="Wrap" Text="{Binding}" />
</DataTemplate>
</Setter.Value>
</Setter>
Upvotes: 0
Views: 6135
Reputation: 66
You can replace the TextBlock
in your HeaderTemplate
with ContentPresenter or remove the HeaderTemplate
to get correct result.
Because of your HeaderTemplate
setting, the header of TVI will display as text block and its data context changes to the stack panel.
Upvotes: 1
Reputation: 383
I managed to fix this by removing the HeaderTemplate
in the xaml.
Then, in my code-behind file I changed the Label
to Textblock
, then set the TextWrapping
and Width
-properties on the Textblock
-object like this:
tree_view.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(@"/ComponentName;component/Resources/Images/warning.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;
}
Upvotes: 0