How to change background Color of Navigationbar programmatically in Xamarin?

杀马特。学长 韩版系。学妹 提交于 2021-02-10 05:51:49

问题


I created a navigationbar in UWP project on Xamarin.

App.xaml.cs
...
public app()
{
  InitializeComponent();
  MainPage = new NavigationPage(new LoginPage()){
    BarBackgroundColor = Color.Black;
  }
}

So If I am in Setting Page, I need to change the color of Navigationbar programmatically.

SettingPage.xaml.cs

...
private void clicked_btn(sender, e) {
  ...
  // how can I get the handle of navigationbar and then change the attribute of one???
}

Is that possible?

Is there a way I can do?


回答1:


Its better not do it, or do it via custom renderers. But below is the forms approach :

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



回答2:


From class definition you can set the bar background color. Like this.

namespace ProyectName
{
    public class MainPage
    {
        public MainPage()
        {
            BarBackgroundColor = Color.FromHex("#484559");
            BarTextColor = Color.White;
        }
    }
}

Or from your App.xml add a ResourceDictionary

<?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="StockIt.App">
    <Application.Resources>
        <ResourceDictionary>
            <Color x:Key="Primary">#484559</Color>
            <Style TargetType="NavigationPage">
                <Setter Property="BarBackgroundColor" Value="{StaticResource Primary}" />
                <Setter Property="BarTextColor" Value="White" />
            </Style>
        </ResourceDictionary>
    </Application.Resources>
</Application>


来源:https://stackoverflow.com/questions/40799154/how-to-change-background-color-of-navigationbar-programmatically-in-xamarin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!