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が適用されません。
下のボタンにも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を継承することが出来ます。