Using the code I can get a content presenter. I would like to locate the first textbox inside it and set the focus accordingly.
Dim obj = TerritoryListViewer.ItemContainerGenerator.ContainerFromItem(myModel)
Using the code I can get a content presenter. I would like to locate the first textbox inside it and set the focus accordingly.
Dim obj = TerritoryListViewer.ItemContainerGenerator.ContainerFromItem(myModel)
You can use VisualTreeHelper
static class to crawl controls tree.
This is how it can be accomplished in c# (sorry I'm VB dyslexic))
T FindFirstChild<T>(FrameworkElement element) where T: FrameworkElement
{
int childrenCount = VisualTreeHelper.GetChildrenCount(element);
var children = new FrameworkElement[childrenCount];
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(element, i) as FrameworkElement;
children[i] = child;
if (child is T)
return (T)child;
}
for (int i = 0; i < childrenCount; i++)
if (children[i] != null)
{
var subChild = FindFirstChild<T>(children[i]);
if (subChild != null)
return subChild;
}
return null;
}
ContentPresenter
has the only child. You get the child simply by
VisualTreeHelper.GetChild(yourContentPresenterObj, 0);
If you need to go deeper - down to a first found TextBox
, then, yes, you use the more comprehensive approach suggested by @alpha-mouse.
Dim myContentPresenter = CType(obj, ContentPresenter)
Dim myDataTemplate = myContentPresenter.ContentTemplate
Dim target = CType(myDataTemplate.FindName("txtQuantity", myContentPresenter), TextBox)
In my case I needed to iterate on all controls of a certain base type placed on a custom canvas which was being used inside an ItemsControl
.
This Linq expression was used to get those controls from within MeasureOverride()
:
var foobarControls =
InternalChildren
.OfType<ContentPresenter>()
.Where(c => VisualTreeHelper.GetChildrenCount(c) > 0)
.Select(c => VisualTreeHelper.GetChild(c, 0))
.OfType<FoobarControlBase>();
This guards against cases where the ContentPresenter
had no children. I found in some instances depending on when this was called the visual tree might not be established and as a result the ContentPresenters
would have no children. (This situation might have been a bug in itself, actually, but nonetheless this code turned out to be reliable.)