ResourceDictionary:System.InvalidCastException

时间:2018-12-11 07:41:24

标签: xaml xamarin xamarin.forms

我抛出异常,我不知道为什么。我的猜测是,我忽略了一些简单的事情。 ResourceSharingPage.xaml.g.cs

中引发了异常

这是我的xaml:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="BookCodedotNet2.ResourceSharingPage">

   <ContentPage.Resources>
        <ResourceDictionary>
            <x:String x:Key="fontSize">Large</x:String>
        </ResourceDictionary>
    </ContentPage.Resources>

    <StackLayout>
        <Button Text=" Carpe diem ">
           <Button.FontSize>
                <StaticResourceExtension Key="fontSize"/>
            </Button.FontSize>
        </Button>
    </StackLayout>
</ContentPage>

如果我删除

           <Button.FontSize>
                <StaticResourceExtension Key="fontSize"/>
            </Button.FontSize>

我可以构建应用。

3 个答案:

答案 0 :(得分:1)

在资源中,尝试如下操作。使用双精度值而不是字符串,因为FontSize是双精度型。

<ResourceDictionary>
        <x:Double x:Key="fontSize">35</x:Double>
    </ResourceDictionary>

答案 1 :(得分:1)

您已经定义了x:String类型的资源。 FontSize不接受类型String的值。它仅接受类型为DoubleNamedSize的值。正如您在对阿卜杜勒·加尼(Abdul Gani)的回答的评论中提到的那样,您应该定义NamedSize

最好使用Style标签,并以这种方式设置Label的样式。如果您想改用Style,请遵循 SushiHangover 的回答over here

答案 2 :(得分:0)

您可以通过以下方式在资源字典中使用NamedSize

   <ContentPage.Resources>
        <ResourceDictionary>
            <Style x:Key="fontSize" TargetType="Button">
                <Setter Property="FontSize" Value="Large" />
            </Style>
            <Color x:Key="NormalTextColor">Blue</Color>
            <Style x:Key="MediumBoldText" TargetType="Button">
                <Setter Property="FontSize" Value="Large" />
                <Setter Property="FontAttributes" Value="Bold" />
            </Style>
        </ResourceDictionary>
    </ContentPage.Resources>

    <StackLayout>
        <Button Text=" Carpe diem "  Style="{StaticResource fontSize}"> </Button>

        <Button Text="Test"
            TextColor="{StaticResource NormalTextColor}"
            Style="{StaticResource MediumBoldText}" />
    </StackLayout>