Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you retrieve a Brush from a ResourceDictionary defined in XAML and apply it to an element in code?

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Microsoft_Windows_Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero">

    <LinearGradientBrush x:Key="ButtonNormalBackgroundBrush"
        StartPoint = "0.5,0"
        EndPoint   = "0.5,1">

        <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 a button as background color in wpf.

 BtnGetBrushes.Background = Brushes.Green;

I want to apply the above color instead of this(Brushes.Green). what should i do for that ?

like image 764
CHANDRA Avatar asked Aug 28 '12 04:08

CHANDRA


People also ask

What is Resourcedictionary?

A resource dictionary is a repository for XAML resources, such as styles, that your app uses. You define the resources in XAML and can then retrieve them in XAML using the {StaticResource} markup extension and {ThemeResource} markup extension s. You can also access resources with code, but that is less common.

How do I add a resource dictionary to XAML?

Tip You can create a resource dictionary file in Microsoft Visual Studio by using the Add > New Item… > Resource Dictionary option from the Project menu. Here, you define a resource dictionary in a separate XAML file called Dictionary1.


2 Answers

Assuming your ResourceDictionary available in the context:

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

or in Code

button.Background = (Brush)FindResource("ButtonNormalBackgroundBrush");
like image 195
Jf Beaulac Avatar answered Oct 19 '22 19:10

Jf Beaulac


BtnGetBrushes.Background = this.Resources["ButtonNormalBackgroundBrush"] as LinearGradientBrush;
like image 33
Hassan Boutougha Avatar answered Oct 19 '22 19:10

Hassan Boutougha