Reputation: 1
I am new to dotnet maui and I can't figuring out how to use the styles defined in the Styles.xaml sheet in the c# markup code.
When I use the following code, my application crashes
new Label
{
Text = "Hello, World!",
Style = (Style)Application.Current.Resources["TitleLabel"]
}
The style exists in the stylesheet:
<Style TargetType="Label" x:Key="TitleLabel"\>
<Setter Property="FontFamily" Value="Montserrat" /\>
<Setter Property="FontSize" Value="20" /\>
<Setter Property="FontAttributes" Value="None" /\>
<Setter Property="TextColor" Value="{StaticResource Black}" /\>
</Style\>
So how do I get this style to work with my c# markup code?
Upvotes: 0
Views: 158
Reputation: 1
I was able to access the Colors.xaml file with the following if-statement:
if (App.Current.Resources.TryGetValue("ReadTag", out var colorvalue))
StatusTagColor = (Color)colorvalue;
Upvotes: 0
Reputation: 8245
Styles can be defined globally by adding them to the app's resource dictionary. See Global styles. So you could put your TitleLabel
in the app level.
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources/Styles/Colors.xaml" />
<ResourceDictionary Source="Resources/Styles/Styles.xaml" />
</ResourceDictionary.MergedDictionaries>
<Style TargetType="Label" x:Key="TitleLabel">
<Setter Property="FontFamily" Value="Montserrat" />
<Setter Property="FontSize" Value="20" />
<Setter Property="FontAttributes" Value="None" />
<Setter Property="TextColor" Value="Black"/>
</Style>
</ResourceDictionary>
</Application.Resources>
Then you could get the style using your code without throwing the error,
new Label
{
Text = "Hello, World!",
Style = (Style)Application.Current.Resources["TitleLabel"]
}
Upvotes: 0