When unit testing a user control with a tree view, I wanted to simulate mouse clicks on tree view items.
But then it turned out that it's not that straightforward to get the control that displays the item
(and that I needed to raise the mouse event for)...
Let's assume that the user control is identified by the variable 'view'.
Next, this user control contains the SomeTreeView tree view.
Finally, we have 2 items that represent the tree view's contents (displayed via binding): someItem and a its child - subItem.
We'll use tree view's ItemContainerGenerator and call .ContainerForItem
to retrieve the control that represents our item in the tree view.
Note though that since we're calling this on the tree view,
this will return a TreeViewItem only for root items and Nothing (null) for non-root items
(thanks go to one of the comments in this discussion).
That's why, to get the tree view item for the sub-node, we need to use the root tree view item's ItemContainerGenerator thus:
Dim treeView As TreeView = view.SomeTreeView
Dim rootTreeViewItem As TreeViewItem =
CType(treeView.ItemContainerGenerator.ContainerFromItem(someItem),
TreeViewItem)
Dim subTreeViewItem As TreeViewItem =
CType(rootTreeViewItem.ItemContainerGenerator.ContainerFromItem(subItem),
TreeViewItem)
And now, mouse clicks can be sent to rootTreeViewItem and/or subTreeViewItem.
Since there's was also a list view in my user control, I also wanted to simulate mouse clicks on items there.
Fortunately, getting ListViewItems for a ListView's item is very similar...
Even simpler, actually, because there's no need to traverse sub-nodes -
all list view items are accessible using list view's ItemContainerGenerator directly:
Dim listView As ListView = view.SomeListView
Dim listViewItem As ListViewItem =
CType(listView.ItemContainerGenerator.ContainerFromItem(listView.Items(i)),
ListViewItem)
(where i is the index of the item we want to get the ListViewItem for).
HTH
Top
|