Tuesday, 14 October 2008

Walking the VisualTree

This isn't all my own code but I thought it might be handy to keep track of some code that walks the VisualTree recursively and also does something with event handlers.

AddHandlers(this);

public void AddHandlers(DependencyObject dependencyObject)
{
int childCount = VisualTreeHelper.GetChildrenCount(dependencyObject);
for (int childIndex = 0; childIndex < childCount; childIndex++)

DependencyObject childObject = VisualTreeHelper.GetChild(dependencyObject, childIndex);

// In this example we're only interested in TextBoxes
if (childObject is TextBox)
{
if ((childObject as TextBox).GetBindingExpression(TextBox.TextProperty).ParentBinding.UpdateSourceTrigger == UpdateSourceTrigger.PropertyChanged)
{
(childObject as TextBox).TextChanged += new TextChangedEventHandler(TextBox_TextChanged);
}
}
AddHandlers(childObject);
}
}

No comments: