How I can get content of TreeViewItem in WPF?

2019-07-31 10:03发布

问题:

For example, my TreeViewItem' header consists of TextBlock and Image. How I can get references to them?

回答1:

I'm not sure if I got you right, but if you want to get visual children of an element, try using VisualTreeHelper.GetChild and VisualTreeHelper.GetChildrenCount.

PS: usually it's more problematic to get a reference to the TreeViewItem itself...

UPDATE (A code example for future generations):

private IEnumerable<DependencyObject> GetChildren(DependencyObject parent)
{
    var count = VisualTreeHelper.GetChildrenCount(parent);
    if (count > 0)
    {
        for (int i = 0; i < count; i++)
            yield return VisualTreeHelper.GetChild(parent, i);
    }
    else
        yield break;
}

private DependencyObject FindInTheVT(DependencyObject parent,Predicate<DependencyObject> predicate)
{
    IEnumerable<DependencyObject> layer = GetChildren(parent);

    while (layer.Any())
    {
        foreach (var d in layer)
            if (predicate(d)) return d;

        layer = layer.SelectMany(x => GetChildren(x));
    }

    return null;
}


回答2:

If you have something like this (created in Xaml or code):

TreeViewItem Item = new TreeViewItem();

StackPanel HeaderLayout = new StackPanel() { Orientation = Orientation.Horizontal };

HeaderLayout.Children.Add(new Image());
HeaderLayout.Children.Add(new TextBlock() { Text = "tv item" });

Item.Header = HeaderLayout;

you can use something like:

foreach (object Control in ((StackPanel)Item.Header).Children)
{
    if (Control is Image)
    {
        //get the image control: Image img = (Image)Control;
    }
    else if (Control is TextBlock)
    {
        //get the textblock: TextBlock tb = (TextBlock)Control;
    }
}

I don't recommend doing this. It will be better if you create a custom header instead (a class that contains Image and TextBlock properties) and assign that to your header, or a custom Template.