NDQuattro
NDQuattro

Reputation: 158

Can't get resource from application level

My app.xaml:

<Application.Resources>
    <RadialGradientBrush x:Key="myBrush">
        <GradientStop Color="#FFC44EC4" Offset="0" />
        <GradientStop Color="#FF829CEB" Offset="1" />
        <GradientStop Color="#FF793879" Offset="0.669" />
    </RadialGradientBrush>
</Application.Resources>

Here I'm trying to use it:

private void btnOK_Click(object sender, RoutedEventArgs e)
    {
        RadialGradientBrush b = (RadialGradientBrush)Resources["myBrush"];
        //b.GradientStops[1] = new GradientStop(Colors.Red,0.0);
    }

But I can't use "b" cause it is null after defining. How can I get that resource?

Upvotes: 4

Views: 2015

Answers (2)

user694833
user694833

Reputation:

As you are trying to reach the resource from an btnOK_Click event, I will assume that method belongs to a window object. So, you are looking for the resource in the wrong location. You have to reference your application's resource dictionary instead.

So, my suggestion is:

private void btnOK_Click(object sender, RoutedEventArgs e) 
{ 
    RadialGradientBrush b = (RadialGradientBrush)Application.Current.Resources["myBrush"]; 
    b.GradientStops[1] = new GradientStop(Colors.Red,0.0); 
} 

Upvotes: 1

NSGaga
NSGaga

Reputation: 14312

You're 'drawing' from the control's resources, try one of these instead...

res = this.FindResource("myBrush"); // this 'walks' the tree and will find it
res = Application.Current.Resources["myBrush"]; // or reference app resources directly
res = App.Current.TryFindResource("myBrush");

hope this helps

Upvotes: 6

Related Questions