我经常使用资源字典,但必须将它们从一个 Xaml 复制并粘贴到另一个 Xaml 才能全部更新,这变得很乏味。我见过的唯一方法是继承样式类,但我不喜欢在 C# 中声明属性的方式(我更喜欢更直观的 XAML 树语法)。有没有办法让一个 XAML 继承另一个 XAML?或者像 LoadXaml() 这样的方法,我可以在创建的每个 Xamarin.Forms.ContentPage 上调用它以从 StylePage 继承?
这是我的样式 xaml 页面:
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Demo.StylePage">
<!-- Shared Properties -->
<ContentPage.Resources>
<ResourceDictionary>
<!-- TitleBar Styles -->
<Style x:Key="TitleBarStyle" TargetType="StackLayout">
<Setter Property="BackgroundColor" Value="#5db3d6"/>
<Setter Property="Padding" Value="15,6"/>
<Setter Property="HeightRequest" Value="44"/>
</Style>
<Style x:Key="TitleBarHeaderStyle" TargetType="Label">
<Setter Property="TextColor" Value="White"/>
<Setter Property="VerticalOptions" Value="CenterAndExpand"/>
<!-- <Setter Property="FontSize" Value="18"/>-->
<Setter Property="HorizontalOptions" Value="FillAndExpand"/>
</Style>
<Style x:Key="EmptyFrameStyle" TargetType="Frame">
<Setter Property="HasShadow" Value="false"></Setter>
<Setter Property="BackgroundColor" Value="Transparent"></Setter>
<Setter Property="Padding" Value="0,0"></Setter>
</Style>
</ResourceDictionary>
</ContentPage.Resources>
</ContentPage>
如何从另一个文件加载此资源字典?感谢您抽出时间,谢尔盖。
最佳答案
ContentPages 支持继承。您始终可以定义一个 BasePage,在那里实现您的资源,然后让每个新的 ContentPage 继承它。虽然我从未通过继承 xaml 来完成此操作,但我曾经在 BasePage 的代码隐藏中共享分析、日志记录等(如下所示)。
我建议尝试类似的方法,并在 BasePage 中实例化资源字典。
基本表单页面:
public class BasePage : ContentPage
{
public BasePage () : base () { }
protected override void OnAppearing ()
{
base.OnAppearing ();
AnalyticsApi.LogPageView ();
AnalyticsApi.LogEvent(Title + " Page Loaded");
}
}
子窗体页面:
<?xml version="1.0" encoding="UTF-8"?>
<local:BasePage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MyApp;assembly=MyApp"
x:Class="MyApp.LoginPage"
Title="{x:Static local:Strings.SignIn}"
BackgroundColor="{x:Static local:Colors.ThemeQuaternary}">
<StackLayout>
...
</StackLayout>
</local:BasePage>
关于c# - Xamarin 表单 XAML : How can I inherit properties from another XAML file like ResourceDictionaries?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30309621/