Dipak
Dipak

Reputation: 1259

How to create global style for Xamarin forms application

I am creating my first xamarin forms application using PCL on Mac machine with Xamarin Studio. I read so many articles to create a global style for application but I am not able to access style which declared in App.xaml.cs file any files inside the application. I mention below bit of code I used. Or if someone have other option to make it easy or anyhow possible please suggest me. Thanks in advance.

App.xaml.cs-

<Application xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="DinePerfect.App">
     <Application.Resources>
        <ResourceDictionary>
            <Style  x:Key="btnStyle"  TargetType="Button">
                <Setter Property="HorizontalOptions" Value="Center" />
                <Setter Property="VerticalOptions" Value="CenterAndExpand" />
                <Setter Property="BorderColor" Value="Lime" />
                <Setter Property="BorderRadius" Value="5" />
                <Setter Property="BorderWidth" Value="5" />
                <Setter Property="WidthRequest" Value="200" />
                <Setter Property="TextColor" Value="Teal" />
            </Style>
        </ResourceDictionary>
    </Application.Resources>
</Application>

Calling style in other file-

<Button Text="Login" Style="{StaticResource btnStyle} TextColor="Black" BackgroundColor="#9C661F"  Clicked="btnLoginClicked" />

Upvotes: 2

Views: 5800

Answers (3)

Ashish Kumar
Ashish Kumar

Reputation: 765

I think you forget to add InitializeComponent(); in your App.cs .When you have a xaml code you have to call InitializeComponent(); in the constructor.

Upvotes: 2

temaby
temaby

Reputation: 86

Looks like while converting your App class to XAML-based you've missed InitializeComponent(); call in constructor.

Upvotes: 5

Marius Junak
Marius Junak

Reputation: 1213

You actually need to set the BackgroundColor in the Style aswell to make the BorderColor work.

From the Button.BorderColor Documentation

This property has no effect if Button.BorderWidth is set to 0. On Android this property will not have an effect unless VisualElement.BackgroundColor is set to a non-default color.

Style:

<ResourceDictionary>
  <Style  x:Key="btnStyle"  TargetType="Button">
    <Setter Property="HorizontalOptions" Value="Center" />
    <Setter Property="VerticalOptions" Value="CenterAndExpand" />
    <Setter Property="BackgroundColor" Value="Black" />
    <Setter Property="BorderColor" Value="Lime" />
    <Setter Property="BorderRadius" Value="5" />
    <Setter Property="BorderWidth" Value="5" />
    <Setter Property="WidthRequest" Value="200" />
    <Setter Property="TextColor" Value="Teal" />
  </Style>
</ResourceDictionary>

Usage in Xaml:

  <Button Text="Login" Style="{StaticResource btnStyle}" />

This Works for me.

Edit: Example Project

Upvotes: 1

Related Questions