38

What does {x:Static} mean in XAML?

Code sample:

<SolidColorBrush Color="{x:Static SystemColors.ControlColor}" />
Mark Cidade
  • 98,437
  • 31
  • 224
  • 236

3 Answers3

71

It is a way to insert any static value into XAML. For example, if I have a class:

namespace A 
{ 
    public class MyConstants 
    {
        public static readonly string SomeConstantString = "BAM!";
    }
}

I can place it into a WPF UI using XAML like this:

<TextBlock Text="{x:Static A:MyConstants.SomeConstantString}" />

Notice, you will have to import the namespace in which MyConstants is defined into your XAML. So in the or element do something like:

xmlns:A="clr-namespace:A"
Szymon Rozga
  • 17,971
  • 7
  • 53
  • 66
  • 2
    Unfortunately this doesn't work in Silverlight: http://stackoverflow.com/questions/3373926/silverlight-4-equivalent-to-wpf-xstatic – Richard Beier Jun 22 '11 at 21:09
6

From MSDN: http://msdn.microsoft.com/en-us/library/ms742135.aspx

References any static by-value code entity defined in a Common Language Specification (CLS) compliant way The property referenced is evaluated prior to loading the remainder of the XAML page and can be used to provide the value of a property in XAML.

TcKs
  • 25,849
  • 11
  • 66
  • 104
0

I found the question XAML - Accessing static fields having an answer which links to the MSDN documentation x:Static Markup Extension. I figured this would still be useful to have on the site.

Community
  • 1
  • 1
Mark Cidade
  • 98,437
  • 31
  • 224
  • 236
  • Yeah, but a simple google search of "x:Static xaml" finds it too! – Andrew Rollings Feb 03 '09 at 16:58
  • At the time I thought "search StackOverflow" not "search Google" and since I got my answer and wanted to get back to coding, I didn't bother to do a cross-reference with Google. I had the code and it worked—I was just curious what as to what it meant. – Mark Cidade Feb 03 '09 at 17:01
  • 1
    That brings up a good point. I wonder if a critical mass will be reached where stackoverflow becomes the first point of call rather than google for the majority of developers. – Andrew Rollings Feb 03 '09 at 17:13
  • 1
    @AndrewRollings well, google search still seems much more functional. Otherwise I'd probably do just that. :) – StayOnTarget Feb 12 '20 at 18:31