Using styles you can define a consistent UI for your app and is a great way to make your XAML files more readable and maintainable in the long term.
Some neat characteristics of styles:
- They are very easy to define.
- Can be inherited to minimize code reuse.
- Can be defined in XAML or in C#.
- You can implement multiple Style Classes so the same control without the need for inheritance.
To define a Style you need to add it as a Resource. You can define them inside specific Pages or within Application class. Here is an example:
Let’s focus on this part:
See how we add the Styles definitions inside the ContentPage’s Resource Dictionary, we can do this too at an application level. The Style definition cannot be more explicit, here are the parts of it:
- The TargetType property: This property is mandatory and defines the type of control we are applying the style to and the properties we get access to set.
- The Setter tags: You have to add a Setter tag per each property you want to set. It has a Property property and a Value property. The IntelliSense in visual studio autocompletes the available properties and values according to the TargetType.
- The x:Key property: This property is optional. When you set this property you’re immediately defining the Style as an explicit type. You would have to set the style property of the control you want to affect.
Styles come in six flavors:
- Global Styles: You can define your styles inside your Application and use them in the whole project
- Implicit Styles: This is the default behavior, as long as you don’t assign a key to the style it is going to be applied implicitly to all controls of the specified TargetType
- Explicit Styles: When you define a style and set a key for it you need explicitly set the Style property of the control you want to apply the style too.
- Dynamic Styles: Although Styles cannot be altered during runtime you can use Dynamic Resources as a workaround to achieve this effect.
- Device Styles: These can only be applied to Labels instances for now and there are six in total, found in the Devices.Styles class: BodyStyle, CaptionStyle, ListItemDetailTextStyle, ListItemTextStyle, SubtitleStyle and TitleStyle
You can inherit from a Style by using the BasedOn property. Styles can be applied to every visual element in Xamarin Forms. If you’re planning on inheriting from a visual element and add styles for it, make sure to either specify the class name in the TargetType or set the ApplyToDerivedTypes to True on the Style tag.
As always I hope this was helpful to you. Until the next one.