views:

1345

answers:

1

I have a user control that applies a style to button, with the style containing a ControlTemplate section. Within the ControlTemplate, there are various UI elements such as an Ellipse and a Path.

If I give those elements -- the Ellipse and Path -- a name with x:Name, can I access them from code behind?

It appears the style's Ellipse and Path are not visible because I get a compile error (C#).

Am I going about this the wrong way?

+2  A: 

Because a template can be instantiated multiple times, it's not possible to bind a generated member via x:Name. Instead, you have to find the named element within the template applied to a control.

Given simplified XAML:

<ControlTemplate x:Key="MyTemplate">
    <Ellipse x:Name="MyEllipse" />
</ControlTemplate>

You would do something like this:

var template = (ControlTemplate)FindResource("MyTemplate");

template.FindName("MyEllipse", myControl);

Or even more simply:

var ellipse = (Ellipse)myControl.Template.FindName("MyEllipse", myControl);

You can read about FrameworkTemplate.FindName.

Some examples and discussion here, here and here.

Drew Noakes
Perfect, thanks a lot!
MattJ
If it is perfect then mark it as the answer.
Vaccano