Home > View Post

Xaml. How to access a static member

This week there'll be a series of short posts about how to do various little titbits in Xaml. I'll be honest, these will serve as much as a quick point of reference for me as they are intended to be interesting content for you. Sorry :)

So, if you want to access a static member inside Xaml here's how. In this example we've simply filled the content of a Label control with the current date and time using the static System.DateTime.Now property.

<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" >
    <Label Content="{x:Static sys:DateTime.Now}" />
</Page>

  1. We had to add a reference to the .NET System namespace into our Xaml using xml namspaces: xmlns:sys="clr-namespace:System;assembly=mscorlib"
  2. We also needed to add the Xaml namespace as we use this to call statics: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  3. Finally, the static is referenced using the Static markup extension, like so: Content="{x:Static sys:DateTime.Now}"
Note that there is no 'databinding' as such here, the time doesn't update. It's only accessed when the page is initially loaded (not even when the Label is repainted).

Interestingly, the above Xaml could also have been written like this:

<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" >
    <Label>
        <x:Static Member="sys:DateTime.Now"/>
    </Label>
</Page>

Tags: Xaml

 
Josh Post By Josh Twist
3:28 AM
26 Feb 2007

» Next Post: Xaml. Using Resources
« Previous Post: Reflector 5.0

Comments are closed for this post.

© 2005 - 2017 Josh Twist - All Rights Reserved.