Wednesday, June 10, 2015

Xamarin Forms: Create a style BasedOn default style defined in app's global resource dictionary

Suppose there’s a style defined in app's global resource dictionary (App.xaml):

<Style TargetType="Label">
    <Setter Property="TextColor" Value="Red" />
</Style>

And this style defined in a page:

<Style x:Key="MyLabelStyle" TargetType="Label">
    <Setter Property="FontSize" Value="14" />
</Style>

If you want MyLabelStyle to inherit the global style, one way is to use this syntax:

<Style x:Key="MyLabelStyle" TargetType="Label" BasedOn=”{StaticResource Xamarin.Forms.Label}”>

otherwise MyLabelStyle will not have the text color red.

Note that this won’t work:
<Style x:Key="MyLabelStyle" TargetType="Label" BasedOn=”{StaticResource {x:Type Label}}”>

Instead of hard coding the Label’s type full name, a nicer way would be to define a custom markup extension which resolves the Label type (something like this)

No comments: