totoro
totoro

Reputation: 3407

How to access a Style outside the code behind file (xaml.cs)?

In code behind (filename.xaml.cs file), I can successfully access the static resources like this:

TextBlock elm = new TextBlock();
elm.Style = (Style)this.Resources["myStyle"];

where Styles.xaml is added to filename.xaml like follows:

<Page.Resources>
    <ResourceDictionary Source="resources/Styles.xaml" />
</Page.Resources>

However, this.Resources["myStyle"] doesn't work in .cs file that isn't associated with any .xaml file. How to access Style.xaml in this case?

Upvotes: 2

Views: 2020

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 156978

You should use FindResource.

Either using this as a FrameworkElement:

elm.Style = (Style)this.FindResource("myStyle");

Or on the Application:

elm.Style = (Style)Application.Current.FindResource("myStyle");

Upvotes: 3

Related Questions