Reputation: 303
When I get the ItemsSource
of my ItemsControl
, it's return me an ObservableCollection
of the view model bounds to my user controls but I want to get an ObservableCollection
of my user controls.
How can I get the user controls contained in my ItemsControl
?
Upvotes: 3
Views: 1857
Reputation: 4327
You can use FindByName of the root control, or go through the visual tree with this function
public static FrameworkElement FindByName(string name, FrameworkElement root)
{
Stack<FrameworkElement> tree = new Stack<FrameworkElement>();
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;
}
Upvotes: 2
Reputation: 12572
You can also have a look at ItemContainerGenerator. You can probably use ContainerFromIndex or ContainerFromItem methods to get the container of each element.
Upvotes: 1
Reputation: 6267
First you need to call ItemsControl.ContainerFromElement to get the "root-control" for each data item displayed. And the you can use the VisualTreeHelper to iterate over the controls.
Upvotes: 1