1

I have a UserControl in a custom DLL assembly where I've defined two static BitmapImage resources that represent the state of data in our ItemsControl. I want to use a converter to set the Source property of an Image to one of the BitmapImage resources depending on some condition. However, I'm not sure how to access the resources from inside the Convert method since I don't have an instance of the control that I'm using the converter on.

I've tried loading the resources into static variables in a static constructor for the converter, which is also in the same DLL, but I haven't been successful.

This fails...

public class MyConverter : IValueConverter
{
    static BitmapImage myFirstResource;
    static MyConverter()
    {
        // This can't seem to find the resource...
        myFirstResource = (BitmapImage)Application.Current.FindResource("MyResourceKey");
    }
}

...but in the XAML, this succeeds, so I know the resource key is valid.

<Image Source="{StaticResource MyResourceKey}" />

I don't know if this makes any difference, but this is in a DLL, not in the EXE. Still, I thought all resources were flattened down to the application depending on where you were executing from.

Mark A. Donohoe
  • 28,442
  • 25
  • 137
  • 286

1 Answers1

0

Found perfect solution here Accessing a resource via codebehind in WPF (better than using Application.Current)

@itsho

You can simply add x:Class to it:

<ResourceDictionary x:Class="Namespace.NewClassName"
                    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
    <ds:MyCollection x:Key="myKey" x:Name="myName" />
</ResourceDictionary>

And then use it in code behind:

var res = new Namespace.NewClassName();
var col = res["myKey"];

Then a little fix should be applied:

@Stephen Ross

But to be able to find resources using it's key I had to call res.InitializeComponent() before attempting to access the key otherwise the object would show no keys and the call to res["myKey"] would return null

Brains
  • 594
  • 1
  • 6
  • 18