How to get brushes from a resource dictionary and apply it to a dynamicallly element in wpf?

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:Microsoft_Windows_Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <LinearGradientBrush x:Key="ButtonNormalBackgroundBrush" EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#C10099FF" Offset="0"/> <GradientStop Color="#C16699CC" Offset="1"/> <GradientStop Color="#C1006699" Offset="0.49"/> </LinearGradientBrush> <ResourceDictionary/> 

Now I want to get LinearGradientBrush from ResourceDictonary and apply it dynamically to the button as the background color in wpf.

  BtnGetBrushes.Background = Brushes.Green; 

I want to apply the above color instead (Brushes.Green). What should I do for this?

+7
source share
2 answers

Assuming your ResourceDictionary is available in context:

 <Button Background="{DynamicResource ResourceKey=ButtonNormalBackgroundBrush}" /> 

or in code

 button.Background = (Brush)FindResource("ButtonNormalBackgroundBrush"); 
+14
source
 BtnGetBrushes.Background = this.Resources["ButtonNormalBackgroundBrush"] as LinearGradientBrush; 
+4
source

All Articles