[英]Use an object (Label) as a template for others in C# / Xamarin.Forms
I have some settings that I want to apply to almost all my Labels
, so my idea is make a templateLabel
with my "default properties" and then copy it to my other labels as I create them. 我有一些设置要应用于几乎所有我的
Labels
,因此我的想法是使用“默认属性”创建一个templateLabel
,然后在创建它们时将其复制到其他标签。
The first that I though was to create a Class that inherits from Xamarin.Forms.Label
where I define my default properties and then make my Labels with it instead of new Label()
. 不过,我首先
Xamarin.Forms.Label
是创建一个从Xamarin.Forms.Label
继承的Class,在其中定义我的默认属性,然后使用它而不是new Label()
来创建new Label()
。 But I have a doubt about it, it will be correct(best? only? possible?) way to do it? 但我对此表示怀疑,这样做是否正确(最佳?仅?可能?)方法? or exist something like.
或存在类似的东西。
var myDefaultPropierties = {Text : "Something", VerticalOptions: LayoutOptions.Center};
Label myFirstLabel = new Label(myDefaultPropierties);
Label mySecondLabel = new Label(myDefaultPropierties);
Creating a subclass of Label
will work, but using a Style, and applying the style to your Label
is cleaner. 创建
Label
的子类可以使用,但是使用样式,然后将样式应用于Label
会更简洁。
Here's a Style example, in XAML. 这是XAML中的一个Style示例。 You can achieve the same result in code, but Styles are mainly meant to be used from XAML:
您可以在代码中获得相同的结果,但是Styles主要用于XAML:
<ContentPage.Resources>
<ResourceDictionary>
<Style x:Key="labelStyle" TargetType="Label">
<Setter Property="Text" Value="Something" />
<Setter Property="VerticalOptions" Value="Center" />
</Style>
</ResourceDictionary>
<ContentPage.Resources>
...
<Label Style="{StaticResource labelStyle}" />
You'll find more info at https://developer.xamarin.com/guides/xamarin-forms/user-interface/styles/introduction/ 您可以在https://developer.xamarin.com/guides/xamarin-forms/user-interface/styles/introduction/中找到更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.