简体   繁体   中英

WPF TreeviewItem header text is set to object type when using stackpanel

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>

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM