Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF set named style elements from code behind?

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?

like image 779
MattJ Avatar asked Oct 05 '09 19:10

MattJ


1 Answers

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.

like image 135
Drew Noakes Avatar answered Oct 18 '22 18:10

Drew Noakes