In this Silverlight application, I am trying to access a resource from Application.Resources in a MainPage class. The resou开发者_如何学编程rce has a x:Name attribute not a x:Key.
I know that I can assign a keyed resource from the Application.Resources by using the following line of code:
grid1.Background = (LinearGradientBrush)Application.Current.Resources["KeyedTwoColorGradient"];
Using this logic I tried to assign a named resource to my grid1.Background and used:
grid1.Background = ((LinearGradientBrush)Application.Current).Resources.NamedTwoColorGradient;
This line of code gives me an error: Cannot convert type 'System.Windows.Application' to 'System.Windows.Media.LinearGradientBrush'
I have tried also different lines but nothing has worked. I could not find the answer from somewhere else so I am here with this question.
In addition, could someone tell me when it would be appropriate to use Named resources and when it would be better to use Keyed?
For starters your brackets were in the wrong place in your example (you were actually casting an application object to a LinearBrush) e.g.:
((LinearGradientBrush)Application.Current)
but the "correct" syntax will auto-complete but will not compile:
(Application.Current as App).KeyedTwoColorGradient;
The problem is that there is no designer.cs equivalent for App.xaml, unlike user controls, so named members are only visible to intellisense but actually have no code-behind property.
You should use keys only for resources.
精彩评论