How I can get content of TreeViewItem in WPF?

ⅰ亾dé卋堺 提交于 2019-12-24 15:33:46

问题


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.



来源:https://stackoverflow.com/questions/10125997/how-i-can-get-content-of-treeviewitem-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!