简体   繁体   中英

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.

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() . 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.

Here's a Style example, in XAML. You can achieve the same result in code, but Styles are mainly meant to be used from 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM