开发者

Using system types in XAML as resources

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 p开发者_运维问答roperty '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?


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>


The problem you are encountering is that on the ColumnDefinition object, the Width property is NOT a double, it is a GridLength structure. If you look at the MSDN documentation for ColumnDefinition.Width you'll see that you cannot assign a double to a ColumnDefinition.Width

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜