Saturday, February 19, 2011

Is there a workaround for the missing FindName method in Silverlight's DataTemplate?

According to the C# compiler and the Silverlight 2 documentation, Silverlight doesn't provide a FindName method for the DataTemplate class. I want to find a Border that's inside a ContentPresenter. What's the best way in SilverLight 2?

From stackoverflow
  • Not totally sure I understand the scenario, but since you mention the DataTemplate I'm assuming you're using a template.

    If you're using a template then what you do is give your border a name (x:Name="border") and then override the OnApplyTemplate method. In that method you use GetTemplateChild and pass the name you used. This will return a reference to your border.

    If you're not use a template and have a reference to the ContentPresenter then you could write a recursive function that looks at the Content property of the child and if it isn't a border then calls your same function on its content.

    MojoFilter : That will work for a ControlTemplate, but you can't really do that inside a DataTemplate, I believe.
  • If the border is inside a DataTemplate, not a ControlTemplate, then the only way I've been able to do that in the past is to use VisualTreeHelper to locate the element I need.

0 comments:

Post a Comment