将XAML中的系统类型用作资源 [英] Using system types in XAML as resources
问题描述
我遇到了这样一种情况,直接在XAML中指定浮点值并将其用作我的多个UI片段的资源非常有用.搜索后,我发现了很多有关如何在XAML中包括适当的程序集(mscorlib)的信息,因此您可以做到这一点.
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.
不幸的是,在尝试执行此操作的一个实例中,我遇到了异常.以下是重新创建情况的以下XAML:
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>
当我尝试编译并运行它时,我得到一个XamlParseException,它提示'120'不是属性'Width'的有效值".
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'".
但是"Width"属性是的两倍,所以为什么不能使用定义的StaticResource进行设置?有人知道该怎么做吗?
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?
推荐答案
否. ColumnDefinition.Width的类型为GridLength,这就是为什么您会收到错误消息.如果您执行以下代码,则应该可以正常工作.
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>
这篇关于将XAML中的系统类型用作资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!