Elisabeth
Elisabeth

Reputation: 21226

How to access a XAML Resource from a CustomControl.cs C# file?

I have a XXXCustomControl.cs class and inside the c# class I want to access via

groupStyle.ContainerStyle = this.FindResource("GroupHeaderStyle") as Style;

the GroupHeaderStyle, but this style is defined somewhere else (wherever that is...)

Now my question: What is the best place to put my GroupHeaderStyle and how to get it via

FindResource from c# code?

Upvotes: 1

Views: 4569

Answers (2)

Fredrik Hedblad
Fredrik Hedblad

Reputation: 84684

If your Style is defined within a ResourceDictionary you can always access it in code behind with

Uri resourceLocater = new Uri("/AssemblyName;component/DictionaryName.xaml", System.UriKind.Relative);
ResourceDictionary resourceDictionary = (ResourceDictionary)Application.LoadComponent(resourceLocater);
groupStyle.ContainerStyle = resourceDictionary["GroupHeaderStyle"] as Style; 

Upvotes: 5

Vlad
Vlad

Reputation: 35594

You should include your XAML file containing the style into your App's resource dictionary as MergedDictionary:

<Application.Resources>
    <ResourceDictionary>
        <!--  here you can add some more resources -->
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="mystyles.xaml"/>
            <!--  here you can add some dictionaries -->
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

See the example here: http://www.wpftutorial.net/MergedDictionaryPerformance.html

Or actually you could put your style definition directly into the App's resources, without merged resource dictionaries. But this way the App's resources usually get bloated quite fast.

Edit:
For the case of library, you don't have an App.xaml available. So you need to do basically the following:

  1. Add a resource dictionary to your project, and define the needed styles there.
  2. In the control's resources, refer to your dictionary as a merged dictionary.

Note that you need to specify the full path ("pack URI") to the dictionary:

<Control.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="pack://application:,,,/YourAssembly;component/Styles.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Control.Resources>

Upvotes: 2

Related Questions