[WPF] How to assign a dynamic resource from code-behind ?

When working on WPF projects, it’s mandatory to assign resources to user interface controls. When you work in XAML, it’s pretty simple: you just need to use the MarkupExtension named StaticResource (or DynamicResource if the resource is going to be modified):

<Button Content="Find Position" Click="Button_Click" Background="{DynamicResource brush}" />

But, how to do the same using code-behind ? The key is to use the method SetResourceReference (http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.setresourcereference.aspx):

<Window.Resources>

    <SolidColorBrush x:Key="brush" Color="Red" />

</Window.Resources>

 

<Button x:Name="btn"Content="Find Position" Click="Button_Click" />

 

this.btn.SetResourceReference(BackgroundProperty, "brush");

As you can see, it’s really simple to use: you define the resource, you define the control and, in code behind, you call the method SetResourceReference and use the following parameters:

  • the DependencyProperty on which the resource will be applied
  • the name of the resource

 

Happy coding !

3 Comments

Comments have been disabled for this content.