Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change background Color of Navigationbar programmatically in Xamarin?

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?

like image 370
Eric Chan Avatar asked Nov 25 '16 06:11

Eric Chan


2 Answers

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;
like image 75
Rohit Vipin Mathews Avatar answered Oct 23 '22 12:10

Rohit Vipin Mathews


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>
like image 35
Samuel Ivan Avatar answered Oct 23 '22 12:10

Samuel Ivan