4
votes

I have a Styles.xaml file where I have declared various colours and styles.

    <SolidColorBrush x:Key="MyColour" Color="#FFFF411E"/>

I want to access this in code, as I have control and I want to bind the background colour to a Property in an object. This easily done, however, the object is created from the response to a server call and the property could be one of many colours. I could define the colour in code, but as I use the same colour for other controls defined in XAML I dont really want to define the same colour twice in the application. So I want a way to be able to access the SolidColorBrush brush in code to be able to use it.

Any idea's how to do this?

2

2 Answers

7
votes

Try this..

 Application.Current.Resources[ "MyColour" ] as SolidColorBrush 
0
votes

first you should have a ResourceDictionary in your xaml or in file.cs.

xaml : <ResourceDictionary Source="Styles.xaml"/>

code : Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri(@"/" + this.GetType().Assembly.GetName().Name + ";component/" + @"Styles.xaml", UriKind.Relative) });

then you can access to it like this

SolidColorBrush mycolor = Resources["MyColour"] as SolidColorBrush;