在C#/ Xamarin.Forms中使用对象(Label)作为其他对象的模板

时间:2016-12-22 21:00:10

标签: c# xamarin xamarin.forms

我有一些设置我想要应用于几乎所有templateLabel,所以我的想法是使用我的“默认属性”制作Xamarin.Forms.Label,然后在创建时将其复制到我的其他标签它们。

我首先要创建一个继承自new Label()的类,我在其中定义默认属性,然后使用它而不是 var myDefaultPropierties = {Text : "Something", VerticalOptions: LayoutOptions.Center}; Label myFirstLabel = new Label(myDefaultPropierties); Label mySecondLabel = new Label(myDefaultPropierties); 创建标签。但我怀疑它,它是正确的(最好的?只有?可能的?)方式吗?或存在类似的东西。

        using (new OffsetWinDialog(this) { PreferredOffset = new Point(75, 75 )})
        using (new SizeWinDialog(this)   { PreferredSize   = new Size(400, 600)})
        {
            DialogResult result = dlgFolderBrowser.ShowDialog();
            if (result == DialogResult.Cancel)
                return;
        }

1 个答案:

答案 0 :(得分:2)

创建Label的子类将起作用,但使用Style,并将样式应用于Label更清晰。

这是一个样式示例,在XAML中。您可以在代码中获得相同的结果,但样式主要用于从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}" />

您可以在https://developer.xamarin.com/guides/xamarin-forms/user-interface/styles/introduction/

找到更多信息