code_junkie

How can I access the ListViewItems of a WPF ListView?

Nov 10th, 2011
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.54 KB | None | 0 0
  1. <ListView x:Name="myList" ItemsSource="{Binding SomeList}">
  2. <ListView.View>
  3. <GridView>
  4. <GridViewColumn>
  5. <GridViewColumn.CellTemplate>
  6. <DataTemplate>
  7. <!-- Focus this! -->
  8. <TextBox x:Name="myBox"/>
  9.  
  10. (myList.FindName("myBox") as TextBox).Focus();
  11.  
  12. private void myList_SelectionChanged(object sender, SelectionChangedEventArgs e)
  13. {
  14. if (myList.SelectedItem != null)
  15. {
  16. object o = myList.SelectedItem;
  17. ListViewItem lvi = (ListViewItem)myList.ItemContainerGenerator.ContainerFromItem(o);
  18. TextBox tb = FindByName("myBox", lvi) as TextBox;
  19.  
  20. if (tb != null)
  21. tb.Dispatcher.BeginInvoke(new Func<bool>(tb.Focus));
  22. }
  23. }
  24.  
  25. private FrameworkElement FindByName(string name, FrameworkElement root)
  26. {
  27. Stack<FrameworkElement> tree = new Stack<FrameworkElement>();
  28. tree.Push(root);
  29.  
  30. while (tree.Count > 0)
  31. {
  32. FrameworkElement current = tree.Pop();
  33. if (current.Name == name)
  34. return current;
  35.  
  36. int count = VisualTreeHelper.GetChildrenCount(current);
  37. for (int i = 0; i < count; ++i)
  38. {
  39. DependencyObject child = VisualTreeHelper.GetChild(current, i);
  40. if (child is FrameworkElement)
  41. tree.Push((FrameworkElement)child);
  42. }
  43. }
  44.  
  45. return null;
  46. }
  47.  
  48. var item = new SomeListItem();
  49. SomeList.Add(item);
  50. ListViewItem = SomeList.ItemContainerGenerator.ContainerFromItem(item); // returns null
  51.  
  52. <DataTemplate x:Name="foo">
  53. <!-- Focus this! -->
  54. <TextBox x:Name="myBox"/>
  55.  
  56. var tb = foo.FindName("myBox");
  57.  
  58. Private Sub SelectAllText(ByVal cell As DataGridCell)
  59. If cell IsNot Nothing Then
  60. Dim txtBox As TextBox= GetVisualChild(Of TextBox)(cell)
  61. If txtBox IsNot Nothing Then
  62. txtBox.Focus()
  63. txtBox.SelectAll()
  64. End If
  65. End If
  66. End Sub
  67.  
  68. Public Shared Function GetVisualChild(Of T As {Visual, New})(ByVal parent As Visual) As T
  69. Dim child As T = Nothing
  70. Dim numVisuals As Integer = VisualTreeHelper.GetChildrenCount(parent)
  71. For i As Integer = 0 To numVisuals - 1
  72. Dim v As Visual = TryCast(VisualTreeHelper.GetChild(parent, i), Visual)
  73. If v IsNot Nothing Then
  74. child = TryCast(v, T)
  75. If child Is Nothing Then
  76. child = GetVisualChild(Of T)(v)
  77. Else
  78. Exit For
  79. End If
  80. End If
  81. Next
  82. Return child
  83. End Function
  84.  
  85. //textbox can be catched like this.
  86. var textBox = ((TextBox)sender);
  87.  
  88.  
  89. EmailValidation(textBox.Text);
  90. }
Add Comment
Please, Sign In to add comment