axbeit
axbeit

Reputation: 883

ResourceDictionary: System.InvalidCastException

I get an Exception throw and I cant figure out why. My guess is that Im overlooking something simple. The Exception gets thrown in ResourceSharingPage.xaml.g.cs

this is my 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>

If I remove

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

I can build the app.

Upvotes: 0

Views: 137

Answers (3)

AbbyWang - MSFT
AbbyWang - MSFT

Reputation: 650

You can use NamedSize in resource dictionary in this way:

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

Upvotes: 0

Tom
Tom

Reputation: 1749

You've defined the resource of type x:String. FontSize doesn't accept values of type String. It only accepts values of type Double or NamedSize. As you mentioned in the comment to Abdul Gani's answer, you should be defining NamedSize.

You are better off using the Style tag and setting the style of your Label that way. Follow SushiHangover's answer over here if you want to use Style instead.

Upvotes: 1

Abdul Gani
Abdul Gani

Reputation: 689

In the resources, try something like below. Use double value instead of string as FontSize is a double.

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

Upvotes: 1

Related Questions