Just a small reminder for myself.
I was actually unaware this was possible in XAML styling, but now that I know it can be done, I will be using this more often đŸ™‚ !
So assume you want to use a custom font in your Xamarin Forms app and you want to preset each Label control with it, you can define this in a Styles.xml like so:
1 2 3 4 5 6 7 |
<OnPlatform x:Key="CenturyGothicFontFamily" x:TypeArguments="x:String"> <On Platform="Android" Value="centurygothic.ttf#Century Gothic" /> </OnPlatform> <Style TargetType="Label"> <Setter Property="FontFamily" Value="{StaticResource CenturyGothicFontFamily}" /> </Style> |
But what do you do when your custom font has no build in Bold feature and you have to rely on a separate custom font for that?
Well, you can let your XAML style check for a trigger and swap the font!
It’s fairly easy, so the code will now look like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<OnPlatform x:Key="CenturyGothicFontFamily" x:TypeArguments="x:String"> <On Platform="Android" Value="centurygothic.ttf#Century Gothic" /> </OnPlatform> <OnPlatform x:Key="CenturyGothicBoldFontFamily" x:TypeArguments="x:String"> <On Platform="Android" Value="centurygothicb.ttf#Century Gothic" /> </OnPlatform> <Style TargetType="Label"> <Setter Property="FontFamily" Value="{StaticResource CenturyGothicFontFamily}" /> <Style.Triggers> <Trigger TargetType="Label" Property="FontAttributes" Value="Bold"> <Setter Property="FontFamily" Value="{StaticResource CenturyGothicBoldFontFamily}" /> </Trigger> </Style.Triggers> </Style> |
And now each time you add the FontAttributes=”Bold” property to your Label control, it will use the correct font type!
Happy coding.
One thought on “Xamarin forms – Switch custom font on Style Trigger”