如何为 Xamarin.Forms 中的自定义控件提供默认样式?

How do you provide a default Style for a Custom Control in Xamarin.Forms?

在 UWP 中,如果我想为自定义控件指定默认样式,我会这样编写代码:

    public PriceControl()
    {
        // This allows the control to pick up a template.
        this.DefaultStyleKey = typeof(PriceControl);
    }

我在 Xamarin.Forms 中找不到对应项。你如何告诉一个自定义控件它应该默认使用一个样式?

只需在控件类型的 App.Xaml 中定义一个样式,不要只给它一个目标类型的键,这样就可以了:

<Application.Resources>
    <ResourceDictionary>
        <Style 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>

只需将按钮替换为您的控件,并将其属性放入 setter 中,这将成为此控件的全局默认样式!