Skip Navigation LinksHome > View Post

Xaml. Using Resources

Yesterday we looked at how to access a static member in Xaml. Today, we'll do something very similar but we'll do it using resources.

In our first example we're going to create a DateTime inside a static resource, and then reference the item in our label, as before

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
    <Page.Resources>
        <sys:DateTime x:Key="date">2007-09-22 10:30</sys:DateTime>
    </Page.Resources>
    <Label Content="{StaticResource date}" />
</Page>

or, predictably, like so...

<Label>
    <StaticResource ResourceKey="date"/>
</Label>
    
StaticResource is similar to using the x:Static notation we used in yesterday's post in that it is loaded just once. You can also use a DynamicResource which is loaded whenever the object is needed (i.e. part of the control is invalidated).

DynamicResource is particularly useful if you're using the SystemColors to paint areas of your application. This will ensure that your application is updated if the user changes any system color settings during the life of your process.

The wide-awake readers will probably have noticed that storing a DateTime in a static isn't the most compelling use of resources and that it can be much more useful for items like brushes and gradients. But you get the idea :D.

Tags: Xaml

 
Josh Post By Josh Twist
11:13 PM
26 Feb 2007

» Next Post: Xaml. Resource Dictionaries
« Previous Post: Xaml. How to access a static member

Comments are closed for this post.

Posted by Eric @ 02 Aug 2011 9:41 AM
Any chance you can add the xaml code that defines the static resource to this page?
I followed the link on statics but was totally confused (WPF newbie but stuck with problem of trying to show an image updated by a different process and so cannot have it locked)

Posted by Eric @ 02 Aug 2011 9:41 AM
Any chance you can add the xaml code that defines the static resource to this page?
I followed the link on statics but was totally confused (WPF newbie but stuck with problem of trying to show an image updated by a different process and so cannot have it locked)

© 2005 - 2014 Josh Twist - All Rights Reserved.