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.