User Interface (UI) in Xamarin

Tram Ho

What is the style in Xamarin Form and how to use it?

What is Style in Xamarin Form?

  • class Style (Xamarin.Forms.Style)
  • Group common UI elements for quick reuse & change such as button types, h1, h2 text types …
  • Style to use: XAML Style or Cascading Style Sheets (CSS)

Using Style with XAML Style:

  • Explicit Styles : apply for a specific object
  • Implicit Styles : Used to apply general to 1 TargetType eg Button / Label …
  • Global Styles : For general use for the entire page (ResourceDictionary at App.xaml), avoid repeating styling between pages, possibly override styles at resource page / resource of each element.
  • Style Inheritance : To inherit from another style, reuse purpose & not duplicate. Use BaseOn:
  • Dynamic Styles : Style will not change after assign. Use DynamicResource to solve this. DynamicResource and StaticResource markup extension are the same, only StaticResource is: single dictionary lookup, and DynamicResource has a link to Dictionary key -> when the dictionary entry linked to dictionary key is changed, it will change according to -> UI will be updated. Proceed through 2 steps:
    • Declare dynamic style XAML file:
    • Processed at code-behind:
  • Device Styles : XF contains 6 types to display for the Label section:
    • BodyStyle
    • CaptionStyle
    • ListItemDetailTextStyle
    • ListItemTextStyle
    • SubtitleStyle
    • TitleStyle

  • Style Classes : to use multiple styles for 1 TargetType: eg BoxView has many Styles:

Using Style with CSS:

  • There is currently no full support for CSS.
  • See more

Theming and usage:

Use to change the entire visual UI of an app, like dark / light theme.

Use DynamicResource to change the theme:

Doing:

  1. Define each theme type in ResourceDictionary
  2. Use themes in apps using DynamicResource
  3. Set default theme in App.xaml file.
  4. Add code to change themes at runtime.

1. Define Theme:

** Dark Theme **

Theme Light

2. Use DynamicResource for the styles:

Use in App.xaml

Use in Content Page

3. Set default theme: App.xml

4. Load the runtime theme:

  • Remove current theme (clear mergedictionary)
  • Load the selected theme and add: MergedDictionaries

demo source (theme)

See also: https://blog.quilv.com/blog/

Share the news now

Source : Viblo