I wanna share…

Using StaticResources in WPF

DownLoad Link: Click Here

Resources are provides a simple way to reuse commonly defined objects and values. If we are defining the resources and we can use that resources number of times. (Just like applying themes and css to web pages).

Resources are two types:

1. Static Resource

2. Dynamic Resource.

StaticResource: StaticResources are resolved at compile time. Use StaticResources when it’s clear that you don’t need your resource re-evaluated when fetching it – static resources perform better than dynamic resources.

DynamicResource: DynamicResources are resolved at runtime. Use DynamicResources when the value of the resource could change during the lifetime of the Application.

I will show you an example regarding Static Resource.

In my WPF application page I’ve one textbox and two ellipses. In Window. Resources I defined the SolidColorBrush and the Style properties.

<Window.Resources>

<SolidColorBrush x:Key=”for1buttoncolor” Color=”Green”></SolidColorBrush>

<SolidColorBrush x:Key=”for2buttoncolor” Color=”CadetBlue”></SolidColorBrush>

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

<Style TargetType=”Border” x:Key=”background”>

<Setter Property=”Background” Value=”Orange”></Setter>

</Style>

<Style TargetType=”TextBox” x:Key=”TitleText”>

<Setter Property=”Background” Value=”White”/>

<Setter Property=”DockPanel.Dock” Value=”Top”/>

<Setter Property=”FontSize” Value=”14″/>

<Setter Property=”Foreground” Value=”#4E87D4″/>

<Setter Property=”FontFamily” Value=”Tahoma”/>

<Setter Property=”Margin” Value=”50,50,50,0″/>

<Setter Property=”Width” Value=”300″></Setter>

</Style>

</Window.Resources>

In above code you can observe x: Key attribute. x: Key uniquely identifies elements that are created and referenced in a XAML-defined dictionary.

Here I’m using above resources. Have a look at below code.

Syntax is :{ StaticResource x:keyName}

<Grid>

<StackPanel>

<Border Style=”{StaticResource background}”>

<DockPanel Height=”360″ Width=”312″>

<TextBox Style=”{StaticResource TitleText}” Height=”28″ Width=”150″></TextBox>

<Ellipse DockPanel.Dock=”Left” HorizontalAlignment=”Left” Height=”73″ Fill=”{StaticResource for1buttoncolor}” Width=”169″></Ellipse>

<Ellipse DockPanel.Dock=”Right” HorizontalAlignment=”Right” Width=”149″ Height=”73″ Fill=”{StaticResource for2buttoncolor}”></Ellipse> </DockPanel>

</Border>

</StackPanel>

</Grid>

Result window looks like this.


 

Advertisements

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: