Xamarin Style Order of Precedence

Viewed 196

I'm playing around with styling in Xamarin.Forms and have a question about the order/rules in which styles are applied. I'm looking for some sort of reference on how this works, but haven't found much other than general "how to style [pick your whatever]" type of posts.

Specifically, I have these two projects:

MyProject.Shared
MyProject.Android

The shared project has my App.xaml and main views/viewmodels, etc.

There's multiple places where I can apply styles:

  • App.xaml resource dictionary
  • MainPage.xaml "inline" (in the xaml elements themselves, not using local resources)
  • MyProject.Android\Resources
  • Custom Renderers (I haven't explored these fully yet)

Precedence between the Application Resources and a given View's Resources seem straightforward enough, but how are the styles between an Android app (or iOS/Win) resolved in comparison with the shared library styles?

Some styles I set seem to be overridden by the android styles, but others seems to ignore android styles and apply the shared styles. Sometimes setting style properties directly via inline xaml doesn't act the way I'd expect, and sometimes with the app level resource styles, only a few settings in the style "take."

Is there some definitive documentation on the order of precedence for these various methods of setting styles, or some formal guidelines that should be followed to properly theme an app?

1 Answers

Great question - I'm looking for a concrete answer from the official Xamarin documentation, and this is the closest that I could find:

Resources can be defined in a ResourceDictionary that's attached to the Resources collection of a page or control, or to the Resources collection of the application. Choosing where to define a ResourceDictionary impacts where it can be used:

  • Resources in a ResourceDictionary defined at the control level can only be applied to the control and to its children.
  • Resources in a ResourceDictionary defined at the page level can only be applied to the page and to its children.
  • Resources in a ResourceDictionary defined at the application level can be applied throughout the application.

But this isn't a complete answer to your question! Here has been my experience with Xamarin.Forms:

  1. App.xaml Resource Dictionary is the most general and will be overridden by anything
  2. Page-level Resource Dictionary is the next most general. It will override any styles defined in App.xaml
  3. Page-level inline styles will override any page-wide styles
  4. Any platform-specific styles (defined in custom renderers, resource dictionary, etc) will override any other style

I hope to update this answer soon with a link to the official remarks on the matter. I recall it being discussed in XAM140, which you can watch if you have a Xamarin University subscription

Related