Using system types in XAML as resources

David picture David · Sep 9, 2010 · Viewed 19.1k times · Source

I have encountered a situation where it would be very useful to specify a floating point value directly in XAML and use it as a resource for several of my UI pieces. After searching around I found a good amount of information on how to include the proper assembly (mscorlib) in your XAML so you can do just that.

Unfortunately, I am getting an exception in one instance where I try to do this. Here is the following XAML that recreates the situation:

<Window x:Class="davidtestapp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:core="clr-namespace:System;assembly=mscorlib"
    Title="MainWindow" Height="350" Width="525">

<Window.Resources>
    <core:Double x:Key="MyDouble">120</core:Double>
</Window.Resources>

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="{StaticResource MyDouble}" />
        <ColumnDefinition Width="40" />
        <ColumnDefinition Width="40" />
    </Grid.ColumnDefinitions>

    <Rectangle Grid.Column="0" Fill="Red" />
    <Rectangle Grid.Column="1" Fill="Green" />
    <Rectangle Grid.Column="2" Fill="Blue" />

</Grid>
</Window>

When I attempt to compile and run this, I get an XamlParseException thrown at me which says that "'120' is not a valid value for property 'Width'".

But the "Width" property is a double, so why can't I set it using the StaticResource which was defined? Does anyone know how to do this?

Answer

ASanch picture ASanch · Sep 9, 2010

No. ColumnDefinition.Width is of Type GridLength which is why you're getting the error. If you do something like the code below, it should work fine.

<Window.Resources>
    <core:Double x:Key="MyDouble">300</core:Double>
    <GridLength x:Key="MyGridLength">20</GridLength>
</Window.Resources>

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="{StaticResource MyGridLength}" />
        <ColumnDefinition Width="40" />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>

    <Rectangle Grid.Column="0" Fill="Red" />
    <Rectangle Grid.Column="1" Fill="Green" />
    <Rectangle Grid.Column="2" Fill="Blue"  Width="{StaticResource MyDouble}"/>

</Grid>