Xamarin共享资源:全局样式和标记扩展



在设置全局属性时,在应用程序(或页面(级别使用XAML Markup Extension而不是Style标记有好处吗?

上下文:

在";XAML基础";他们给出了以下例子:

ORIGINAL
<Button Text="Do this!"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand"
BorderWidth="3"
Rotation="-15"
TextColor="Red"
FontSize="24" />
... OTHER SIMILAR BUTTONS ...
CLEAN
<ContentPage.Resources>
<ResourceDictionary>
<LayoutOptions x:Key="horzOptions"
Alignment="Center" />
<LayoutOptions x:Key="vertOptions"
Alignment="Center"
Expands="True" />
<x:Double x:Key="borderWidth">
3
</x:Double>
<x:Double x:Key="rotationAngle">-15</x:Double>
</ResourceDictionary>
</ContentPage.Resources>
<Button Text="Do this!"
HorizontalOptions="{StaticResource horzOptions}"
VerticalOptions="{StaticResource vertOptions}"
BorderWidth="{StaticResource borderWidth}"
Rotation="{StaticResource rotationAngle}"
TextColor="{StaticResource textColor}"
FontSize="{StaticResource fontSize}" />

在Style的文档中,他们给出了以下示例:

RESOURCE DICTIONARY CONTAINING BUTTON STYLE set in App.cs
<Application.Resources>
<ResourceDictionary>
<Style x:Key="buttonStyle" 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>
BUTTON WITH STYLE APPLIED IN A ContentPage
<Button Text="These buttons" Style="{StaticResource buttonStyle}" />

很明显,它们在语法上很相似,但第二种方法就不那么冗长了,那么第一种方法有什么意义呢?

显然,根据文档,它们是不同的定义。

XAML标记扩展

XAML标记扩展构成XAML中的一个重要功能,允许将属性设置为从其他源间接引用的对象或值。XAML标记扩展对于共享对象和引用整个应用程序中使用的常量特别重要,但它们在数据绑定中具有最大的实用性。

Xamarin.Forms中的全局样式

通过将样式添加到应用程序的资源字典中,可以使其全局可用。这有助于避免页面或控件之间的样式重复。

您将看到XAML标记扩展的范围大于全局样式,但是全局样式只是资源样式的特殊用途。

最新更新