Reputation: 10015
I am trying to retrieve a solid color brush pre-defined in a resource dictionary (Styles.xaml) from C#.
The problem is that when i run the following code nothing happens:
private void LinkContinue_MouseEnter(object sender, MouseEventArgs e)
{
this.LinkContinue.Background = (SolidColorBrush)Resources["HoverColorBrush"];
}
However if I set the background in code explicitly it runs fine:
private void LinkContinue_MouseLeave(object sender, MouseEventArgs e)
{
this.LinkContinue.Background = new SolidColorBrush(Colors.Gray);
}
Any ideas?
Upvotes: 0
Views: 3892
Reputation: 10015
So the answer was Application.Current.Resources["ResourceName"] as SolidColorBrush
! Who would've known that the Resources object points to the resource dictionary for the page? UGHHH
Upvotes: 3
Reputation: 34250
The syntax Resources["HoverColorBrush"]
looks up a resource stored in the resources of the current object. In this case, the resources of the instance of the class that contains the method LinkContinue_MouseEnter
.
If you want to use the same lookup mechanism that {StaticResource HoverColorBrush}
would use, you need to use the FindResource
method instead:
But, as luck would have it, Silverlight does not support FindResource
and so you need to either look up the resource directly in the ResourceDictionary
defined in Styles.xaml
, or roll your own FindResource
.
Here is a blog article on this topic with sample code:
Upvotes: 4