Having a page and wanting to search for a control that is bound to a certain property I traverse the VisualTree
. This is done on Page.Loaded
event (based on this question). When traversing the Visual Tree
I encounter the textbox I was looking for (in a testcase) but when using
var be = textbox.GetBindingExpression(System.Windows.Controls.TextBox.TextProperty);
be
is null.
Does WPF still has to execute / render some visual controls and the bindings. And if so, which event could I hook onto to traverse the VisualTree with "activated" bindings?
btw: I already have it working for a sample project where I traverse the VisualTree
on a button click. (page is loaded and bindings are fully functional then)
EDIT
XAML code:
<dxe:TextEdit Grid.Row="2" Grid.RowSpan="1" Grid.Column="5" Style="{DynamicResource {x:Static cbc:CustomStyle.QuestionTextEditStyle}}" Text="{Binding Path=Voorletters, Mode=TwoWay, ValidatesOnDataErrors=true}"/>
Code behind:
private void BasePage_Loaded(object sender, RoutedEventArgs e)
{
if (!String.IsNullOrEmpty(_focusControlBindedToProperty))
{
this.FindVisualElementBindedTo(this, _focusControlBindedToProperty);
}
}
private void FindVisualElementBindedTo(Visual visual, String propertyName)
{
try
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(visual); i++)
{
// Retrieve child visual at specified index value.
Visual childVisual = (Visual)VisualTreeHelper.GetChild(visual, i);
if (childVisual is System.Windows.Controls.Primitives.TextBoxBase)
{
System.Windows.Controls.Primitives.TextBoxBase tbb = (System.Windows.Controls.Primitives.TextBoxBase)childVisual;
BindingExpression be = tbb.GetBindingExpression(System.Windows.Controls.TextBox.TextProperty);
if (be != null && be.ParentBinding != null && be.ParentBinding.Path.Path == propertyName)
{
tbb.Focus();
tbb.SelectAll();
return;
}
}
FindVisualElementBindedTo(childVisual, propertyName);
}
}
catch { }
}