【问题标题】:Using system types in XAML as resources使用 XAML 中的系统类型作为资源
【发布时间】:2011-04-10 10:59:12
【问题描述】:

我遇到过一种情况,直接在 XAML 中指定一个浮点值并将其用作我的几个 UI 片段的资源非常有用。在四处搜索后,我发现了大量有关如何在 XAML 中包含正确程序集 (mscorlib) 的信息,以便您可以做到这一点。

不幸的是,在我尝试执行此操作的一个实例中遇到了异常。以下是重现这种情况的 XAML:

<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>

当我尝试编译并运行它时,我收到一个 XamlParseException 向我抛出,它说“'120' 不是属性 'Width' 的有效值”。

但是“Width”属性是双精度的,那为什么我不能使用定义的StaticResource来设置呢?有谁知道怎么做?

【问题讨论】:

    标签: wpf xaml resourcedictionary staticresource mscorlib


    【解决方案1】:

    没有。 ColumnDefinition.Width 是 GridLength 类型,这就是您收到错误的原因。如果你执行下面的代码,它应该可以正常工作。

    <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>
    

    【讨论】:

    • 谢谢!有效。这很有帮助。我没有意识到它是 GridLength 类型的。
    【解决方案2】:

    您遇到的问题是,在ColumnDefinition 对象上,Width 属性是NOT 一个double,它是一个GridLength 结构。如果您查看MSDN documentation for ColumnDefinition.Width,您会发现您无法将双精度分配给 ColumnDefinition.Width

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多