Xamarin.Forms: reusing resources in XAML using Styles

Datetime:2016-08-23 03:58:42          Topic:          Share

Previously, I’ve blogged about creating a custom Behavior in Xamarin.Forms. The sample published on GitHub initially used the default template available in Visual Studio which instantiates the Application singleton from C# using the following App class:

usingMultiTouch.Views;
usingXamarin.Forms;
 
namespace MultiTouch
{
    public class App : Application
    {
        public App()
        {
            MainPage = new SamplePage();
        }
 
        protected overridevoid OnStart()
        {
            // Handle when your app starts
        }
 
        protected overridevoid OnSleep()
        {
            // Handle when your app sleeps
        }
 
        protected overridevoid OnResume()
        {
            // Handle when your app resumes
        }
    }
}

This is a great approach, however very often it is useful to define common resources in XAML and reuse them across the application using  Styles .

To achieve this, It’s possible to transform the App class in a partial one and add a new App.xaml source file containing a resource dictionary to be shared:

<?xmlversion="1.0" encoding="utf-8" ?>
<Applicationxmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            x:Class="MultiTouch.App">
  <Application.Resources>
    <ResourceDictionary>
      <OnPlatform x:Key="PagePadding" x:TypeArguments="Thickness" iOS="0,20,0,0" />
      
      <Stylex:Key="PageStyle" TargetType="ContentPage">
        <Setter Property="Padding" Value="{StaticResource PagePadding}"></Setter>
      </Style>
    </ResourceDictionary>
  </Application.Resources>
</Application>

In this code, I’ve defined a new resource with a specific Padding  to be applied only on iOS via the OnPlatform class, and an explicit style named PageStyle targeting ContentPage types.

The modified code behind is now taking care of parsing/loading the XAML (via the InitializeComponent() call) and then creates an instance of  SamplePage :

usingMultiTouch.Views;
usingXamarin.Forms;
 
namespace MultiTouch
{
    public partialclass App : Application
    {
        public App()
        {
            InitializeComponent();
 
            MainPage = new SamplePage();
        }
 
        protected overridevoid OnStart()
        {
            // Handle when your app starts
        }
 
        protected overridevoid OnSleep()
        {
            // Handle when your app sleeps
        }
 
        protected overridevoid OnResume()
        {
            // Handle when your app resumes
        }
    }
}

The page can now consume the new style specifying Style=”{StaticResource PageStyle}” ( dynamic resources are also supported):

<?xmlversion="1.0" encoding="utf-8" ?>
<ContentPagexmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            xmlns:behaviors="clr-namespace:MultiTouch.Behaviors;assembly=MultiTouch.Behaviors"
            x:Class="MultiTouch.Views.SamplePage" Style="{StaticResource PageStyle}">
  <ContentPage.Content>
    <Grid>
      <ContentView>
          <ContentView.Content>
            <ImageSource="desert.jpg" BindingContext="{Binding}">
              <Image.Behaviors>
                <behaviors:MultiTouchBehaviorIsScaleEnabled="True" IsTranslateEnabled="True" />
              </Image.Behaviors>
            </Image>
          </ContentView.Content>
      </ContentView>
    </Grid>
  </ContentPage.Content>
</ContentPage>

This is a basic example of using styles in Xamarin.Forms: a complete coverage of the various options is available on the Xamarin official documentation .

The source code is available for download here .