RunningCSharp

MS系開発者による、雑多な記事。記事は所属企業とは関係のない、個人の見解です。

Xamarin:Key指定なしのStyle(デフォルトのStyle)を継承する方法

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App.MainPage"
             xmlns:local="clr-namespace:App">
  <ContentPage.Resources>
    <ResourceDictionary>
      <Style TargetType="Button">
        <Setter Property="BackgroundColor" Value="Red"/>
      </Style>
    </ResourceDictionary>
  </ContentPage.Resources>
  
  <StackLayout Orientation="Vertical">
    <Button Text="Test1"/>
    <Button>
      <Button.Style>
        <Style TargetType="Button">
          <Setter Property="Text" Value="Test2"/>
        </Style>
      </Button.Style>
    </Button>
  </StackLayout>
</ContentPage>

上記のようなxamlを記述した場合、ContentPageの子要素でButtonを定義した場合、基本的には自動的にContent.Resourcesで定義したKeyを指定していないStyleが適用されます。そのため、上のボタンは何も指定していなくともBackgroundが赤くなります。

しかし、下のボタンはButtonのStyleプロパティに新規でStyleを指定しているため、Content.Resourcesで定義したStyleが適用されません。

f:id:ys-soniclab:20160906222106p:plain

下のボタンにもContent.ResourcesのStyle(つまり、その場所での暗黙的なStyle)を継承させるには、

WPFではBasedOn="{StaticResource {x:Type Button}}"のような書き方をしましたが、Xamarinでは下記のようにBasedOnを記述します。

    <Button>
      <Button.Style>
        <Style TargetType="Button" BasedOn="{StaticResource Xamarin.Forms.Button}">
          <Setter Property="Text" Value="Test2"/>
        </Style>
      </Button.Style>
    </Button>

Buttonを上記のように書き換えると、標準のStyleを継承することが出来ます。

f:id:ys-soniclab:20160906222120p:plain