There is a page, it connects styles via xaml in this way:
<ContentPage.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <themes:MainStyles /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </ContentPage.Resources> The dictionary itself looks like this:
<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="MyMobApp.Themes.MainStyles"> <OnPlatform x:Key="BaseFont" x:TypeArguments="x:String"> <On Platform="Android" Value="cuprum_standard.ttf#Cuprum" /> <On Platform="iOS" Value="Cuprum" /> <On Platform="UWP, WinRT, WinPhone" Value="Assets/Fonts/cuprum_standard.ttf#Cuprum" /> </OnPlatform> <Style x:Key="Grey" TargetType="Label"> <Setter Property="FontFamily" Value="{StaticResource BaseFont}" /> <Setter Property="FontSize" Value="12" /> <Setter Property="TextColor" Value="#A0A0A0" /> </Style> <Style x:Key="h1" TargetType="Label"> <Setter Property="TextColor" Value="#000000" /> <Setter Property="FontSize" Value="14" /> <Setter Property="FontFamily" Value="{StaticResource BaseFont}" /> </Style> In XAML, I apply styles like this:
<Label Text="{Binding Date}" Margin="10,10,10,0" HeightRequest="13" Style="{StaticResource Grey}" /> Everything is working. But then it became necessary to add Label to the page dynamically, to which you need to stick the Gray style, for example. Googled and found such a logical option:
this.Wrapper.Children.Add(new Label { Text = this._Event.Date, Style = Application.Current.Resources["Grey"] as Style }); BUT, it throws a System.NullReferenceException: Object reference not set to an instance of an object. exception System.NullReferenceException: Object reference not set to an instance of an object.
I bow to the fact that in my case, not just a Resource, but a matter of MergedDictionaries. How, then, to apply a style from C # code?