I have a textblock inside the ContentTemplate of an Expander. I want to access that textblock in my code behind file. This is what I have tried so far
I've tried your code, it's almost fine. I've tried testing it on such as a Button first, it works OK. However for the Expander
, it's more complex. There are 2 notices here:
IsExpanded = true
).UpdateLayout
explicitly)So the code should be:
yourExpander.IsExpanded = true;
yourExpander.UpdateLayout();
//now use your method
var textBlock = FindVisualChild(yourExpander);
Your code can be shorten more like this:
private childItem FindVisualChild(DependencyObject obj)
where childItem : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if(child is childItem) return (childItem)child;
childItem childOfChild = FindVisualChild(child);
if (childOfChild != null) return childOfChild;
}
return null;
}
Note that child
will never be null
. Because the GetChildrenCount()
already limits the range of existing children, so the child
should exist at the specified index i
.