-1

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.

Angevil
  • 469
  • 3
  • 10
  • `LoadContent()` creates new elements based on the template. What particular element are you trying to change the appearance of? – mm8 Feb 10 '21 at 20:36
  • Well its hard to say precisely without posting a big chunk of code, but if it creates a new instance, that explains why my modifications make no change to the program whatsoever. Do you have any idea how I could get the actual "SliderButton_ButtonControl" that has been defined in the style applied to `myTemplatedButton`? – Angevil Feb 10 '21 at 20:39
  • Please see my answer. – mm8 Feb 10 '21 at 20:40

1 Answers1

1

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;
mm8
  • 163,881
  • 10
  • 57
  • 88
  • I find no such thing as "Template" in FrameworkElement – Angevil Feb 10 '21 at 20:43
  • I thought `myTemplatedButton` was a `Button`. Isn't it? Cast it to `Control` or `Button`. Only controls have templates so this should be safe. – mm8 Feb 10 '21 at 20:44
  • `((Control)myTemplatedButton).Template.FindName(...)` – mm8 Feb 10 '21 at 20:46
  • I tried this and realized that my LoadContent() on first line does not return the Button but the main Grid of the Style itself, using `Ellipse ellipse = this.Template.FindName("SliderButton_ButtonControl", this) as Ellipse;` fixed it, thanks! – Angevil Feb 10 '21 at 20:51