我遇到了这样一种情况,如果能够直接在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来设置它呢?有谁知道怎么做吗?