views:

7110

answers:

3

I'm trying to access a resource dictionary in a UserControl code-behind via C# and I'm having little success.

Merged Dictionary:

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Resources/BiometricDictionary.xaml" />                
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>

Embedded Dictionary:

<UserControl.Resources>
    <BitmapImage x:Key="imageDefault">/Resources/Images/default_thumb.png</BitmapImage>
    <BitmapImage x:Key="imageDisconnected">/Resources/Images/disconnect_thumb.png</BitmapImage>
    <BitmapImage x:Key="imageFailed">/Resources/Images/failed_thumb.png</BitmapImage>
    <BitmapImage x:Key="imageSuccess">/Resources/Images/success_thumb.png</BitmapImage>
</UserControl.Resources>

Code behind:

        var resourceDictionary = new ResourceDictionary();
        resourceDictionary.Source = new Uri("/Resources/BiometricDictionary.xaml", UriKind.Relative);

I've tried all of the examples and helpful tips but coming up short. Right now, success would be the ability to load the dictionary. Any suggestions?

A: 

So, you have a ResourceDictionary defined in a UserControl's assembly, and would like to access it from that UserControl's code-behind?

You should be able to. However, if the code you listed is in the constructor, you may not have access to the resource dictionary (might not be loaded yet). Try adding that same code to your UserControl's "loaded" event, and see if that works. If you're simply trying to access a resource, such as a style or template, using the "FindResource" or "TryFindResource" functions directly from your class should work as well (i.e. you don't need to have an object of type "ResourceDictionary").

Hope that helps!

Pwninstein
A: 

To access one of your UserControl's XAML resources in your codebehind, all you need to do is access the Resources property of the UserControl. Something like this:

BitmapImage myImage = (BitmapImage)this.Resources["imageDefault"];

Though, the preferred method is to use FindResource(), which will search the entire logical tree for a match to the key, rather than just the object it is called on.

BitmapImage myImage = (BitmapImage)this.FindResource("imageDefault");
PeterAllenWebb
A: 

d'Oh...after compiling to the local bin so that references are relative, I implemented the pack URI solution found here: http://stackoverflow.com/questions/338056/wpf-resource-dictionary-in-a-separate-assembly and then FindResource(x:key value here).

@PeterAllenWeb, @Pwninstein, thanks for your quick responses and getting me thinking again.