我想将静态资源添加到我的UWP XAML代码中,如下所示:
<Page
x:Class="Appnap.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Appnap"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.Resources>
<local:MyCoffee CoffeeName="Esperso" Price="10.0" x:Key="okkk">
</local:MyCoffee>
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBlock Name="test" Text="{Binding CoffeeName,Source={StaticResource okkk}}" Margin="155,150,-155,-150" />
</Grid>
我还添加了咖啡课,如下所示:
namespace Appnap
{
public partial class MyCoffee
{
public string CoffeeName { get; set; }
public decimal Price { get; set; }
}
}
当我尝试编译代码时,出现错误,无法将值分配给价格(XamlCompiler错误WMC0055:无法将文本值“ 10.0”分配给类型为“十进制”的属性“价格”),我尝试了:10、10.0和10M,但没有任何变化。
正如XamlCompiler错误所说,这里的问题是XamlCompiler无法将文本值'10 .0'转换为Decimal
。
在UWP XAML中,它使用称为类型转换器的功能来执行转换,以将字符串值转换为该值的强类型版本。类型转换器只是一个具有一个功能的类,即将一个字符串值转换为一个强类型。通用Windows平台API中内置了其中的几种。有关更多信息,请参见:UWP-005-了解类型转换器。
但是,Decimal
内置的UWP API中没有Type Converter for 。XamlCompiler无法将您在XAML中设置的值解析为decimal
。在WPF中,我们可以使用TypeConverter
class为不受支持的类型创建自己的TypeConverter。但这在UWP中不受支持。
解决方法是,您可以MyCoffee
在代码隐藏中初始化并Binding
在XAML中使用,如下所示:
在后台代码中,DataContext
为页面或TextBlock设置
public MainPage()
{
this.InitializeComponent();
//Set DataContext for the page
this.DataContext = new MyCoffee { CoffeeName = "Esperso", Price = 10M };
//Or for the TextBlock
//test.DataContext = new MyCoffee { CoffeeName = "Esperso", Price = 10M };
}
在XAML中,使用
<TextBlock Name="test" Margin="155,150,-155,-150" Text="{Binding CoffeeName}" />
这是我们用于绑定的最常用方法。
但是,如果你想使用MyCoffee
的StaticResource
,你可以设置Price
的类型,double
这是由现有的类型转换器的支持。但是,这可能会失去一些价格准确性,这取决于您的特定数据。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句