Using system types in XAML as resources

♀尐吖头ヾ 提交于 2019-12-22 01:27:08

问题


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?


回答1:


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>



回答2:


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



来源:https://stackoverflow.com/questions/3680146/using-system-types-in-xaml-as-resources

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!