WPF set style elements from code behind?

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

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

It looks like the Ellipse and Path style is not showing because I am getting a compilation error (C #).

Am I going about it wrong?

+7
styles wpf controltemplate
source share
1 answer

Since a template can be created several times, it is not possible to link the generated element via x:Name . Instead, you need to find the named element in the template applied to the control.

For 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 simpler:

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

You can read about FrameworkTemplate.FindName .

Some examples and discussion here , here and here .

+18
source share

All Articles