【问题标题】:Change Navigation Bar Color for Single Page in Xamarin在 Xamarin 中更改单个页面的导航栏颜色
【发布时间】:2021-06-19 09:50:11
【问题描述】:

在我的 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;

更新

【问题讨论】:

  • 您好,您尝试的代码是正确的。我想可能是你放错了代码。您能否重新检查一次重新分配 BarBackgroundColor 颜色的位置。您需要在需要修改导航栏颜色的屏幕的构造函数中重新分配颜色。
  • 实际上我在MainActivity.cs 页面中使用了Window.SetStatusBarColor(Android.Graphics.Color.White);.. 我删除了它并再次尝试上面的代码和答案中的代码(下面).. 没有任何效果..
  • @Karamazov 例如,您想从 contentpage1 导航到 contentpage2,因此您在 contentpage2 OnAppearing() 上添加代码,然后在 contentpage2 OnDisappearing() 上返回默认导航栏颜色。
  • 是的..我想要这个..我尝试了下面答案中的代码..但它没有做任何改变..
  • @Karamazov 将这些代码添加到 contentpage 2 private Color barColor; protected override void OnAppearing() { base.OnAppearing(); var navigationPage = Application.Current.MainPage as NavigationPage; barColor = navigationPage.BackgroundColor; navigationPage.BarBackgroundColor = Color.Black; }

标签: c# .net xamarin xamarin.forms


【解决方案1】:

试试这个,

在所有页面的 App.xaml 中

<Application.Resources>
    <ResourceDictionary>


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

        </Style>

    </ResourceDictionary>
</Application.Resources>

让我们说第 2 页的颜色为 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;
    }

【讨论】:

  • 很难说,您是否删除了 styles.xml 中的文本?然后是 App.xaml 中的第一部分,以及 Page2.xaml.cs 中的第二部分
  • 是的,我删除了文本并添加了这两个代码 sn-ps。
  • 我唯一能想到的是,在黑暗主题的光上是否一样
  • 抱歉没听懂..你更喜欢哪个主题?
  • 做了一个小项目,这就是你的意思。 github.com/borisoprit/Testbar/tree/master
猜你喜欢
  • 2015-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-29
  • 1970-01-01
  • 2019-11-13
  • 1970-01-01
相关资源
最近更新 更多