假设您有以下 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 中的所有文本都将为蓝色 - .outer
div 中的所有 div 都将继承该属性,无论它们嵌套在多远。
我可以在 Xamarin.Forms 中做类似的事情吗?或者,如果我在 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.Forms - 像 CSS 一样的嵌套样式继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37302836/