Sunday, 4 August 2013

WPF - Binding Resource at Runtime

Accessing Resource at runtime through Code
   In WPF we can access the resource at runtime and apply the value of resource to the control. In this example we are going to see the resource which is mention in stack panel resource and later bind it to the button background property.

  If FindResource() doesn’t find the resource key, then an exception is thrown, If we don’t knew whether the available of resource then use TryFindResource() this will return null if the resource is not available instead of error.

In the above image you can see the error resource not found, this is because the key is wrong.


    <StackPanel Name="stackcontainer">
            <LinearGradientBrush x:Key="mygradient" StartPoint="0.5,0" EndPoint="0.5,1">
                <GradientStop Offset="0.0" Color="LightGray"/>
                <GradientStop Offset="0.14" Color="Cyan"/>
                <GradientStop Offset="0.7" Color="DarkCyan"/>
        <Button Name="bt1" Width="150" HorizontalAlignment="Center"  VerticalAlignment="Center"  Height="40" Click="bt1_Click">Apply Resource</Button>

C# Code

   private void bt1_Click(object sender, RoutedEventArgs e)
      Control cnt = sender as Control;
      cnt.Background = cnt.TryFindResource("mygradient") as Brush;


From this article you can learn the binding of resource value at the run time through code..