How can I access the ListViewItems of a WPF ListView?

前端 未结 6 947
天命终不由人
天命终不由人 2020-12-09 10:33

Within an event, I\'d like to put the focus on a specific TextBox within the ListViewItem\'s template. The XAML looks like this:



        
6条回答
  •  醉酒成梦
    2020-12-09 11:14

    I noticed that the question title does not directly relate to the content of the question, and neither does the accepted answer answer it. I have been able to "access the ListViewItems of a WPF ListView" by using this:

    public static IEnumerable GetListViewItemsFromList(ListView lv)
    {
        return FindChildrenOfType(lv);
    }
    
    public static IEnumerable FindChildrenOfType(this DependencyObject ob)
        where T : class
    {
        foreach (var child in GetChildren(ob))
        {
            T castedChild = child as T;
            if (castedChild != null)
            {
                yield return castedChild;
            }
            else
            {
                foreach (var internalChild in FindChildrenOfType(child))
                {
                    yield return internalChild;
                }
            }
        }
    }
    
    public static IEnumerable GetChildren(this DependencyObject ob)
    {
        int childCount = VisualTreeHelper.GetChildrenCount(ob);
    
        for (int i = 0; i < childCount; i++)
        {
            yield return VisualTreeHelper.GetChild(ob, i);
        }
    }
    

    I'm not sure how hectic the recursion gets, but it seemed to work fine in my case. And no, I have not used yield return in a recursive context before.

提交回复
热议问题