Yogesh Bhadauriya's Blog

Do what ever you Like!

[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 !

Advertisement

April 19, 2010 - Posted by | .Net 3.5, WPF |

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.