Total Pageviews

Monday, April 19, 2010

[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>
    Key="brush" Color="Red" />
Window.Resources>


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 !

Blog Archive

Ideal SQL Query For Handling Error & Transcation in MS SQL

BEGIN TRY BEGIN TRAN --put queries here COMMIT; END TRY BEGIN CATCH IF @@TRANCOUNT>0 BEGIN SELECT @@ERROR,ERRO...