如何在Xamarin Forms NavigationPage中更改背景颜色

9

我试图更改导航栏在导航页面中的背景颜色,我使用以下代码:

using System;
using System;
using Xamarin.Forms;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
namespace P
{
public class App : Application
{
    public App ()
    {
 MainPage = new NavigationPage(new LoginPage());
    }
    protected override void OnStart ()
    {
    }
    protected override void OnSleep ()
    {
    }
    protected override void OnResume ()
    {
        // Handle when your app resumes
    }
   }
  }

我该如何做到这一点?

4个回答

14

只需设置 NavigationPage 实例的 BarBackgroundColor 属性:

new NavigationPage(new LoginPage()) { BarBackgroundColor = Color.Green };

10

如果您想在XAML中设置全局样式,可以类似于以下代码:

<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="Sample.App">
    <Application.Resources>

        <ResourceDictionary>
            <Style TargetType="NavigationPage">
                <Setter Property="BarBackgroundColor" Value="#ff5733"/>
                <Setter Property="BarTextColor" Value="White"/>
            </Style>
        </ResourceDictionary>

    </Application.Resources>
</Application>

很难在没有更多信息的情况下确定。您是否将其包含在app.xml文件中?如果仍然存在问题,建议您开启一个单独的问题。 - James John McGuire 'Jahmic'
太棒了!这个可以没有任何自定义就能工作。 - Nick Turner

1
<Application.Resources>
    
    <ResourceDictionary>
        <!--Global Styles-->
        <Color x:Key="NavigationPrimary">Green</Color>
        <Style TargetType="NavigationPage">
            <Setter Property="BarBackgroundColor" Value="{StaticResource NavigationPrimary}" />
            <Setter Property="BarTextColor" Value="White" />
        </Style>
    </ResourceDictionary>
</Application.Resources>
  1. 基本上进入App.xaml文件
  2. 将此代码粘贴到那里
  3. 在这部分中,根据您的喜好更改颜色 绿色

0
如果您想在每个页面上使用不同的颜色更改NavigationBar的BackgroundColor。 您可以在每个页面/视图的Codebehind上执行以下操作。
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace NewApp.Cross.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class NewView : ContentPage
    {
        public NewView()
        {
            InitializeComponent();
            Title = "PageTitle"

            NavigationPage.SetHasBackButton(this, false);

            ((NavigationPage)Application.Current.MainPage).BarBackgroundColor = Color.Black;
            ((NavigationPage)Application.Current.MainPage).BarTextColor = Color.OrangeRed;
        }
    }
}

它可以在Android和iOS上运行。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接