Search code examples
c#wpfbackgrounddependency-propertiesuielement

Getting the Background of a UIElement or sender


I'm trying to find a generic way to set the Background property on a UIElement.

I'm not having much luck...

Here's what I have so far (trying to use reflection to get the BackgroundProperty).

  Action<UIElement> setTheBrushMethod = (UIElement x) =>
  {
    var brush = new SolidColorBrush(Colors.Yellow);
    var whatever = x.GetType().GetField("BackgroundProperty");
    var val = whatever.GetValue(null);
    ((UIElement)x).SetValue(val as DependencyProperty, brush);
    brush.BeginAnimation(SolidColorBrush.ColorProperty, new ColorAnimation(Colors.White, TimeSpan.FromSeconds(3)));
  };
  setTheBrushMethod(sender as UIElement);

The thing is...it works for something like a TextBlock, but does not work for something like a StackPanel or a Button.

"whatever" ends up being null for StackPanel or Button.

I also feel like there should be an easy way to generically set the Background. Am I missing obvious?

Background only appears to be available on System.Windows.Controls.Control but I can't cast to that.


Solution

  • Your reflection call is actually wrong: you are looking for the Background PROPERTY, not the BackgroundProperty DEPENDENCYPROPERTY

    Here is what should be your var whatever :

    var whatever = x.GetType().GetProperty("Background").GetValue(x);
    x.GetType().GetProperty("Background").SetValue(x, brush);
    

    And this will work fine

    SIDE NOTES:

    I strongly advice you to get rid of useless var and write the actual type you are waiting for (in this case, a Brush), that will make your code much easier to read

    Also, why can't you just work on a Control and not an UIElement ? Seems pretty rare to me

    Cheers!