Xamarin.Forms Projects
上QQ阅读APP看书,第一时间看更新

Setting an application-wide background color

Styles are a great way to apply styling to elements. They can be applied either to all elements of a type or to the elements referenced by a key, if you add an x:Key attribute:

  1. Open App.xaml in the .NET Standard project.
  2. Add the following XAML, which is in bold, to the file:
<ResourceDictionary>
<Style TargetType="NavigationPage">
<Setter Property="BarBackgroundColor" Value="#A25EBB" />
<Setter Property="BarTextColor" Value="#FFFFFF" />
</Style>

<Style x:Key="FilterButton" TargetType="Button">
<Setter Property="Margin" Value="15" />
<Setter Property="BorderWidth" Value="1" />
<Setter Property="BorderRadius" Value="6" />
<Setter Property="BorderColor" Value="Silver" />
<Setter Property="TextColor" Value="Black" />
</Style>

<Color x:Key="CompletedColor">#1C8859</Color>
<Color x:Key="ActiveColor">#D3D3D3</Color>
</ResourceDictionary>

The first style we are going to apply is a new background color and text color in the navigation bar. The second style will be applied to the filter button. We can define a style by setting the TargetType that instructs Xamarin.Forms which type of object this style can be applied to. We can then add one or more properties that we want to set. The result is the same as if we had added these properties directly to the element in the XAML code.

Styles that lack the x:Key attribute will be applied to all instances of the type defined in TargetType. The styles that have a key must be explicitly assigned in the XAML of the user interface. We will see examples of this when we define the filter button in the next section.