Saturday, 16 March 2013

DYNAMIC RESOURCE BINDING


1. Open vs 2010->File->New->Project
2. Select Windows Template->Wpf(WIndowBased)/Wpf(XBAPs) as per your requirement
3. You will find default code like this.


<Window x:Class="programically.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
      <Grid>
     </Grid>
</Window>


4. Create a Window Resource using <Window.Resources> Tag under <Window> Tag

<Window x:Class="programically.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
    <Window.Resources>
        <SolidColorBrush x:Key="red" Color="red" />
    </Window.Resources>
     <Grid>

     </Grid>
</Window>

5. Replace the <Grid></Grid> tag with <StackPanel></StackPanel> and put a DockPanel  with name "myDock" under StackPanel Tag.

<Window x:Class="programically.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
    <Window.Resources>
        <SolidColorBrush x:Key="red" Color="red" />
    </Window.Resources>

     <Grid>
         <StackPanel>
                <DockPanel x:Name="mydock" Height="90">
                </DockPanel>
         </StackPanel>
     </Grid>


</Window>



6. Now, we are going to access this resource Key from code behind file,switch to the code behind file
and paste the following coding under the load event of page .

 this.mydock.SetResourceReference(DockPanel.BackgroundProperty, "red");


7. Press F5 and test the result .



No comments:

Post a Comment