Xamarin.Forms-类似CSS的嵌套样式继承



假设您有以下HTML:

<div class="outer">
    Some text
    <p>Some more text</p>
    <div class="inner">
        Yet more text <span>and even more text</span>
    </div>
</div>

如果我应用以下CSS:

.outer {
    color: blue;
}

然后,该html中的所有文本都将是蓝色的——.outerdiv中的所有div都将继承该属性,无论它们嵌套在其中多远。

我可以在Xamarin做一些类似的事情吗。表格?或者,例如,如果我在StackLayout中有一堆标签,我是否必须为每个标签设置样式。仅有一个的标签

我选择创建一个静态样式类,然后将样式应用于XAML本身或构造函数中的控件(如果适用)。这样,您就可以对项目进行单独样式设置,或者为可重复使用的控件设置标准样式。

样式类别

    public static class AppStyling
        {
         public static readonly Style Style_Page_Standard = new Style(typeof(Page))
            {
                Setters =
                {
                    new Setter {Property =  Xamarin.Forms.Page.BackgroundColorProperty, Value = AppStyling.Color_GlobalBackground},
                    new Setter {Property = Xamarin.Forms.Page.PaddingProperty, Value = AppStyling.Padding_StandardPage},
                }
            };
        public static readonly Style Style_Button_Standard = new Style(typeof(Button))
        {
            Setters =
            {
                new Setter {Property = Xamarin.Forms.Button.BackgroundColorProperty, Value = AppStyling.Color_ButtonBackground},
                new Setter {Property = Xamarin.Forms.Button.TextColorProperty, Value = AppStyling.Color_ButtonText},
                new Setter {Property = Xamarin.Forms.Button.FontSizeProperty, Value = AppStyling.Font_Button},
                new Setter {Property = Xamarin.Forms.Button.BorderColorProperty, Value = AppStyling.Color_ButtonBorder},
                new Setter {Property = Xamarin.Forms.Button.BorderRadiusProperty, Value = AppStyling.Radius_StandardButtonCorner},
                new Setter {Property = Xamarin.Forms.Button.BorderWidthProperty, Value = 3},
            }
        };
}

控制实施

public Custom_Button()
        {
            this.Style = AppStyling.Style_Button_Standard;
        }

XAML中的实现

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MyNameSpace.Views.MyContentPage"
             xmlns:styling="clr-namespace:MyNameSpace.Styling;assembly=MyNameSpace"
             Title="MyContentPageTitle"
             Style="{x:Static styling:AppStyling.Style_Page_Standard}">

Xamarin文档中也有需要研究的全球资源声明。

https://developer.xamarin.com/guides/xamarin-forms/user-interface/styles/application/

现在您可以将CSS与Xamarin一起使用。窗体来设置XAML的样式。这是David Rettenbacher的一个名为XamlCSS的库。

它还支持WPF和UWP项目。

截至目前,为Xamarin。表单,建议使用预发布版本2.0.0-pre1。你可以从这里下载。XamlCSS的文档可以在这篇wiki文章中找到。或者只需在PackageManager控制台中使用Install-Package XamlCSS.XamarinForms -Version 2.0.0进行安装。

获得理解的最好方法是尝试这个示例项目。

有关更多信息,请参阅本论坛帖子。

最新更新