Search code examples
c#wpfxamlcode-behindframeworkelement

Templated FrameworkElement impossible to modify from code behind


Context

I have a Style redefining the ControlTemplate applied on a FrameworkElement. On given events, I want to be able to modify some properties of the content of the ControlTemplate (from code behind, not binding).

I get wanted FrameworkElement with this piece of code that I found here: Access control in style from code

FrameworkElement myTemplatedButton = this.Template.LoadContent() as FrameworkElement;
Ellipse ellipse = myTemplatedButton.FindName("SliderButton_ButtonControl") as Ellipse;

This seems to find the element I'm looking for as I dont get any error and the reference is well set.

Problem

However, when I try to update Properties like this

ellipse.Fill = Brushes.Red;
ellipse.Visibility = Visibility.Hidden;

Nothing changes in my application, and if I put a breakpoint in the code before re-triggering the event, I can see that the Property Visibility (for example) has been reset to Visibility.Visible.

It's like if the application was overriding my changes as soon as the function returns, and I have no idea why.


Solution

  • LoadContent() creates new elements based on the template.

    If you want to modify an existing element, you should call the FindName method of the template of this one:

    Ellipse ellipse = myTemplatedButton.Template
        .FindName("SliderButton_ButtonControl", myTemplatedButton) as Ellipse;