How can I access the ListViewItems of a WPF ListView?

前端 未结 6 943
天命终不由人
天命终不由人 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:10

    As others have noted, The myBox TextBox can not be found by calling FindName on the ListView. However, you can get the ListViewItem that is currently selected, and use the VisualTreeHelper class to get the TextBox from the ListViewItem. To do so looks something like this:

    private void myList_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (myList.SelectedItem != null)
        {
            object o = myList.SelectedItem;
            ListViewItem lvi = (ListViewItem)myList.ItemContainerGenerator.ContainerFromItem(o);
            TextBox tb = FindByName("myBox", lvi) as TextBox;
    
            if (tb != null)
                tb.Dispatcher.BeginInvoke(new Func(tb.Focus));
        }
    }
    
    private FrameworkElement FindByName(string name, FrameworkElement root)
    {
        Stack tree = new Stack();
        tree.Push(root);
    
        while (tree.Count > 0)
        {
            FrameworkElement current = tree.Pop();
            if (current.Name == name)
                return current;
    
            int count = VisualTreeHelper.GetChildrenCount(current);
            for (int i = 0; i < count; ++i)
            {
                DependencyObject child = VisualTreeHelper.GetChild(current, i);
                if (child is FrameworkElement)
                    tree.Push((FrameworkElement)child);
            }
        }
    
        return null;
    }
    

提交回复
热议问题