在 Xamarin 中更改单页的导航栏颜色

问题描述

在我的 Xamarin 应用程序中,我在 styles.xml 页面中设置了导航栏(状态栏/顶部栏)的颜色。并且所有页面的导航栏颜色变为白色

styles.xml

<?xml version="1.0" encoding="utf-8" ?>
<resources>

  <style name="MainTheme" parent="MainTheme.Base">
  </style>
  <!-- Base theme applied no matter what API -->
  <style name="MainTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- colorPrimaryDark is used for the status bar -->
    <item name="colorPrimaryDark">#FFFFFF</item>
  </style>

</resources>

现在,我只想将单个内容页面中导航栏的颜色更改为黑色

我按照此 answer内容页面中粘贴代码,但颜色没有改变。

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

更新

enter image description here

解决方法

试试这个,

在所有页面的 App.xaml 中

<Application.Resources>
    <ResourceDictionary>


        <Style TargetType="NavigationPage">
            <Setter Property="BarBackgroundColor" Value="White"/>
            <Setter Property="BarTextColor" Value="Black"   />

        </Style>

    </ResourceDictionary>
</Application.Resources>

让我们说 Page 2 使用 Color Black ,然后再次使用 OnDisappearing White

 public partial class Page2 : ContentPage
{
    public Page2()
    {
        InitializeComponent();
    }

    protected override void OnAppearing()
    {
        base.OnAppearing();
        var navigationPage = Application.Current.MainPage as NavigationPage;
        navigationPage.BarBackgroundColor = Color.Black;
    }

    private async void Button_Clicked(object sender,EventArgs e)
    {
        await Navigation.PushAsync(new Page2DetailsPage());
    }

    protected override void OnDisappearing()
    {
        base.OnDisappearing();

        var navigationPage = Application.Current.MainPage as NavigationPage;
        navigationPage.BarBackgroundColor = Color.White;
    }