【问题标题】:Set background color of page with style用样式设置页面的背景颜色
【发布时间】:2023-03-29 08:13:01
【问题描述】:

我在App.xaml 中定义了以下显式样式:

<Application.Resources>
    <ResourceDictionary>
      <Style TargetType="ContentPage" x:Key="PageStyle">
        <Setter Property="BackgroundColor" Value="#ff0000" />
      </Style>
    </ResourceDictionary>
</Application.Resources>

我要显示的页面嵌入到NavigationPage 中,并且派生自ContentPage。它具有以下隐式样式,而这里使用ContentPage 而不是我的派生类型(实际上我使用派生类型,但我没有尝试过,但效果相同):

<ContentPage.Resources>
    <ResourceDictionary>
      <Style TargetType="ContentPage" BasedOn="{StaticResource PageStyle}" />
    </ResourceDictionary>
</ContentPage.Resources>

但是页面的背景没有改变。它始终显示平台的默认背景颜色。如果我为Button 使用样式,则会应用该样式。我试过NavigationPageContentPagePageVisualElement,但背景始终是默认背景。

如果我明确设置颜色

<ContentPage.BackgroundColor>
    <Color>Red</Color>
</ContentPage.BackgroundColor>

this.BackgroundColor = Color.Red;

颜色已应用。

【问题讨论】:

  • 必答题:设计器中没有设置背景?
  • 目前没有可用的设计器。您只能使用 XML 或 C#。
  • 改写:BackgroundColor 依赖属性是否在 XML 或 C# 中的任何位置显式设置?
  • BackgroundColor 依赖属性到底是什么意思?我已经在应用程序级别定义了一个样式(使用背景设置器),我想在页面上使用它。在这种情况下,背景颜色在 XML 中设置。
  • 可以帮助this主题。

标签: xaml xamarin xamarin.forms


【解决方案1】:

像这样将样式应用到您的 ContentPage:

<ContentPage (...) Style="{StaticResource PageStyle}">

【讨论】:

  • 您知道为什么从显式样式转换为隐式样式对页面不起作用吗?
  • 遗憾的是我不知道。如果您不想在每个 ContentPage 上设置背景,则创建一个继承自 ContentPage 的新类,使用 App.xaml 中的样式在其 xaml/constructor 中设置背景,然后使用此类而不是 ContentPage。这有点天真,但如果最简单的解决方案不起作用,那么......这是一个具有这种行为的页面,但可能最后一篇文章是你的:bugzilla.xamarin.com/show_bug.cgi?id=27659
【解决方案2】:

我认为这种行为的原因是SomePage(在我的例子中)是ContentPage 的子类。我发现在documentation for implicit styles

但是,Style 并没有应用于 CustomEntry 实例,它是一个子类条目

所以隐式样式不适用于子类。但每一页都是ContentPage 的子类。只能使用Michał Ż的解决方案。

【讨论】:

    【解决方案3】:

    您可以全局分配它,您必须将ApplyToDerivedTypes 设置为true。这是一个例子:

    <Style TargetType="ContentPage" ApplyToDerivedTypes="True">
        <Setter Property="BackgroundColor" Value="#4A4A4A" />
    </Style>
    

    现在所有继承 ContentPage 的类都将具有这种背景颜色。

    【讨论】:

    • 直截了当的回答...谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 2019-06-21
    • 1970-01-01
    • 2014-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多