1

I have the following code:

ControlTemplate ct = (ControlTemplate)XamlReader.Load(validXmlString); 

Now I need to obtain the control that this template created, in my case, a Button. I have searched far and wide and can't find a simple explanation for how this is done.

Please note that for some unexplained reason, Microsoft provided a FindControl() method for ControlTemplate in WPF, but not in Silverlight. I've read that this can be done with the VisualTreeHelper, but I have yet to see an explanation for how.

3
  • You really shouldn't be doing that... Commented Jan 11, 2012 at 14:54
  • Unhelpful response, Silverlight is massively flawed in its implementation of the DataGrid, and it's left me no choice but to do this. Do you have knowledge of how to do this? If so, please share it. Commented Jan 11, 2012 at 14:59
  • No choice? Maybe you are overlooking something, just what are you trying to achieve overall? Commented Jan 11, 2012 at 18:46

1 Answer 1

1

Below you will find an example that loops through the Visual Tree recursively and finds all buttons adding them to a collection. You can check the name of the button etc.. and do what you need to do. I just used a collection as an example, as I found a quick sample on it.

public MainPage() { InitializeComponent(); this.Loaded += new RoutedEventHandler(MainPage_Loaded); } void MainPage_Loaded(object sender, RoutedEventArgs e) { List<UIElement> buttons = new List<UIElement>(); GetChildren(this, typeof(Button), ref buttons); } private void GetChildren(UIElement parent, Type targetType, ref List<UIElement> children) { int count = VisualTreeHelper.GetChildrenCount(parent); if (count > 0) { for (int i = 0; i < count; i++) { UIElement child = (UIElement)VisualTreeHelper.GetChild(parent, i); if (child.GetType() == targetType) { //DO something with the button in the example added to a collection. You can also verify the name and perform the action you wish. children.Add(child); } GetChildren(child, targetType, ref children); } } } 

Hope this helps

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.