How to set a property to a DynamicResource reference in code

I recently needed to set a dependency property to a DynamicResource reference in code.  It’s easy enough to do in XAML, but a quick Google search turned up nothing which explained how to do it in the code-behind.  Hopefully this blog post will rectify that situation.

The magic method is FrameworkElement’s SetResourceReference.  Here is a quick demo:


DynamicResource reference in code (XAML)


DynamicResource reference in code (C#)

About these ads

3 Responses to How to set a property to a DynamicResource reference in code

  1. Massimiliano says:

    Great Josh! it’s great thing!

  2. anon says:

    Doesn’t work in VS2008 for me, but this worked (almost, not all resource keys worked?!):

    (Brush)new BrushConverter().ConvertFromString(“SomeResourceKey”);

  3. Abdolhosein V. Ebrahimi says:

    Great, but is there any sort of GetResourceReference by which I can find the resource name which is used to set say for example Background of control?

    I need it to give ability to change font, color,… on the fly:
    1) user clicks on control ( in customization mode)
    2) It selected font and color and …


Get every new post delivered to your Inbox.

Join 298 other followers

%d bloggers like this: