Search code examples
c#wpfresourcedictionary

How to get a dynamic resource key name programmatically?


My program loads at runtime XAML file with following declaration of WPF control. The XamlReader.Load(...) method is used.

<TextBlock Name="txMy" Text="{DynamicResource ResourceKey=MyTextFromRes}"/>

It works perfect and shows text from dynamic dictionary correctly. Now I need to know NAME of KEY that resource dictionary at runtime because XAML file can be various. I need to play with related dictionary values.

How can I get a string with name of resource key ("MyTextFromRes" in this sample) at runtime in c# code?


Solution

  • Create the following helper method:

    public string GetDynamicResourceKey(DependencyObject dObj, DependencyProperty dp)
    {
        var value = dObj.ReadLocalValue(dp);
        var converter = new ResourceReferenceExpressionConverter();
        var dynamicResource = converter.ConvertTo(value, typeof(MarkupExtension)) as DynamicResourceExtension;
        return dynamicResource?.ResourceKey as string;
    }
    

    Now, use it with your TextBlock:

    var resourceKey = GetDynamicResourceKey(txMy, TextBlock.TextProperty);
    

    I adapted this solution from here.