2
votes

Newly working in Xamarin and it appears that if I try to set a style for ContentPage nothing happens

Xaml in App.xaml's ResourceDictionary:

<Style TargetType="ContentPage">
    <Setter Property="BackgroundColor" Value="#f8f8f8"/>
</Style>

I know that the app.xaml style is being read. I have a button style that has been applied globally. But I cannot seem to affect any change on ContentPage. No errors are being reported.

How can I globally set the backgroundcolor?

I've read that this might be a bug, but that was a year ago. If it is still a bug is there a workaround?

2
Please read this post, it could be usefull, there is a bug related to this and some workaround too forums.xamarin.com/discussion/34798/…Tomasz Kowalczyk
I've tried this, but am having a hard time then figuring out what the xaml in my main page would look likecrthompson
@TomaszKowalczyk, thanks for the help. You pointed me to the right path.crthompson
super so maybe vote up for my comment? ;)Tomasz Kowalczyk
@TomaszKowalczyk, I'll go one better as comment upvotes do nothing.crthompson

2 Answers

3
votes

Following code in App.xaml works for me:

<Style TargetType="ContentPage" ApplyToDerivedTypes="True">
   <Setter Property="BackgroundColor" Value="Lime" />
</Style>

Note:

  • You should NOT use attribute x:Key in Style.
  • You should add ApplyToDerivedTypes="True"

I found solution at https://putridparrot.com/blog/styles-in-xamarin-forms/

1
votes

Following the tip by @Tomasz Kowalczyk using the example xaml from this rather incomplete post:

In app.xaml ResourceDictionary put this style:

<Style x:Key="defaultPageStyle" TargetType="ContentPage">
   <Setter Property="BackgroundColor" Value="#f8f8f8"/>
</Style>

The base class is called BaseContentPage

public class BaseContentPage : ContentPage
{
    public BaseContentPage()
    {
        var style = (Style)Application.Current.Resources["defaultPageStyle"];
        Style = style;
    }
}

Then to tie it all together in each xaml.cs class:

namespace MyNamespace
{
    public partial class MyXamlPage: BaseContentPage

And .xaml file

<local:BaseContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:MyNamespace;assembly=MyNamespace"
         x:Class="MyNamespace.MyXamlPage"