WPF set named style elements from code behind?

MattJ picture MattJ · Oct 5, 2009 · Viewed 10.5k times · Source

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?

Answer

Drew Noakes picture Drew Noakes · Oct 5, 2009

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.