Wednesday, April 6, 2011

How to use a defined brush resource in XAML, from C#

So far I have this

<UserControl.Resource>
 <LinearGradientBrush x:Key="KeyDownBrush" .....>

Now I would like to access this defined resource when a key is pressed and replace the current objects fill with the KeyDownBrush, in C#.

I've tried this.Resource.Contains("KeyDownPress") and have been able to get True returned so I presume I am almost there but I'm not sure how to access the object and Parse it correctly to a Brush instance.

Any guidance would be appreciated.

From stackoverflow
  • From within your UserControl:

    var brush = this.Resources["KeyDownBrush"] as LinearGradientBrush;
    

    Should do the trick.

    Sebastian Gray : Thanks Matt. I thought I must be close, I just couldn't seem to find an example for this in the documentation where I was looking. For anyone else the C# I used looks like System.Windows.Media.LinearGraidentBrush aBrush = (System.Windows.Media.LinearGradientBrush)this.Resources["KeyDownBrush"]; aRectangle.Fill = aBrush;

0 comments:

Post a Comment