user8813514
user8813514

Reputation:

Xamarin Froms XAML get color from App Resource

I made a color resource in Xamarin Forms App like this:

<Application ...>
    <Application.Resources>
        <Color x:Name="ColorLineSeparator">#cccccc</Color>
    </Application.Resources>
</Application>

I want to use it in MainPage.xaml like this:

<BoxView
            HeightRequest=".5"
            HorizontalOptions="FillAndExpand"
            BackgroundColor="[HOW TO USE IT HERE?]"/>

Original WPF handle this issue something like this:

<Button Background="{DynamicResource ResourceKey=ColorLineSeparator}" />

However it seems not working in Xamarin Forms Page. It showing this error:

No property, bindable property, or event found for 'ResourceKey', or mismatching type between value and property.

Upvotes: 0

Views: 256

Answers (2)

EvZ
EvZ

Reputation: 12169

First of all you have to declare Application.Resources the right way:

<Application ...>
    <Application.Resources>
        <ResourceDictionary>
            <Color x:Key="ColorLineSeparator">#cccccc</Color>
        </ResourceDictionary>
    </Application.Resources>
</Application>

All the resources declared this way are actually static:

<BoxView BackgroundColor="{StaticResource ColorLineSeparator}"/>

There is a great official article about this stuff.

P.S.: Enabling XAMLC may help you to identify such mistakes in the future.

Upvotes: 1

FetFrumos
FetFrumos

Reputation: 5944

Add x:Key in your resource:

<Color x:Key="MyColor">#cccccc</Color>

and use it:

      <BoxView
        HeightRequest=".5"
        HorizontalOptions="FillAndExpand"
        BackgroundColor="{StaticResource MyColor}"/>

Upvotes: 0

Related Questions