Xamarin.Forms元素样式自动应用实现及父类样式不生效问题排查
Xamarin.Forms ContentPage样式自动应用及派生类生效解决方案
问题描述
1. 样式需手动设置才生效
我在App.xaml中定义了如下ContentPage样式:
<Style x:Key="ContentPageStyle" TargetType="ContentPage"> <Setter Property="BackgroundColor" Value="{AppThemeBinding Light=#FFFFFF, Dark=#020202}" /> </Style>
该样式仅在手动为ContentPage元素设置Style属性时才会生效,示例代码:
<views:BasicView xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:views="clr-namespace:SkeletonApp.View.Page;assembly=SkeletonApp" x:Class="SkeletonApp.Example.MainPage" Style="{StaticResource ContentPageStyle}" Title="Home"> <!-- Content markup --> </views:BasicView>
请问如何通过设置TargetType让样式自动应用?是否可行?
2. 派生类BasicView设置样式不生效
我有一个继承自ContentPage的父类BasicView,在其XAML中设置上述样式却不生效,相关代码如下:
CS文件:
namespace SkeletonApp.View.Page { public partial class BasicView : ContentPage { public BasicView() { } } }
XAML文件:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="SkeletonApp.View.Page.BasicView" Style="{StaticResource ContentPageStyle}"> </ContentPage>
附完整的原App.xaml代码:
<?xml version="1.0" encoding="utf-8" ?> <Application x:Class="SkeletonApp.App" xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"> <Application.Resources> <Color x:Key="TransparentColor">Transparent</Color> <!-- Light colors --> <Color x:Key="LightPageBackgroundColor">Magenta</Color> <!-- Dark colors --> <Color x:Key="DarkPageBackgroundColor">Lime</Color> <Style x:Key="ContentPageStyle" TargetType="ContentPage" ApplyToDerivedTypes = "True"> <Setter Property="BackgroundColor" Value="{AppThemeBinding Light={StaticResource LightPageBackgroundColor}, Dark={StaticResource DarkPageBackgroundColor}}" /> </Style> </Application.Resources> </Application>
解决方案
修改App.xaml中的样式定义,去掉x:Key属性并添加ApplyToDerivedTypes="True",即可实现样式自动应用到所有ContentPage及其派生类:
<Style TargetType="ContentPage" ApplyToDerivedTypes="True"> <Setter Property="BackgroundColor" Value="{AppThemeBinding Light={StaticResource LightPageBackgroundColor}, Dark={StaticResource DarkPageBackgroundColor}}" /> </Style>
注意事项
- 不要为Style设置
x:Key属性:设置x:Key后样式变为“显式样式”,仅能通过手动引用生效;移除x:Key后样式成为“隐式样式”,会自动应用到所有匹配TargetType的元素。 - 必须添加
ApplyToDerivedTypes="True":该属性会让隐式样式自动应用到TargetType的派生类(比如这里的BasicView),否则样式仅对直接的ContentPage实例生效。
内容的提问来源于stack exchange,提问作者DarkVss
相关产品推荐
相关产品推荐

