0

I am trying to dynamically change BarBackgroundColor in App.cs, but cannot because of

System.NullReferenceException: 'Object reference not set to an instance of an object.'

   public static void changeBackground() {
        ((NavigationPage)Current.MainPage).BarBackgroundColor = Color.Red;  //error here
    }

    public App()
    {
        InitializeComponent();
        MainPage = new NavigationPage(new NotesPage());
    }

I tried to solve that making static NavBar and making it MainPage = Navbar. However, i still had that error.

  • public App() { MainPage = new NavigationPage(new Page1()) { BarBackgroundColor = Color.Gray }; } – Anand May 28 '20 at 04:42

2 Answers2

0

What I usually do to avoid this mess and a navigation mess is that I keep my navigation page as a static public variable in my app class and use it,

A similar thing I do here:

https://stackoverflow.com/a/49175351/7462031

In your App.Xaml.cs add

    public static NavigationPage NavigationPage { get; private set; }

Initialize it:

    NavigationPage = new NavigationPage(new Home());

Push Pages into it:

    App.NavigationPage.PushAsync(page);

Change bar color:

    App.NavigationPage.BarBackgroundColor= YourColor;
FreakyAli
  • 13,349
  • 3
  • 23
  • 63
0

If want to modify color of navigation bar dynamically , you can define color key of navigation bar in App.xaml as follow :(Also can add some default color key here)

<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="AppZXing.App">
    <Application.Resources>
        <!-- Application resource dictionary -->
        <ResourceDictionary>
            <Color x:Key="navbarredcolor">#FFFFFF</Color>
            <!--White color -->
            <Color x:Key="navbarwhitecolor">#191919</Color>
            <!--Black color -->
            <Style ApplyToDerivedTypes="true"
                   TargetType="NavigationPage">
                <!--ApplyToDerivedTypes means for all content pages -->
                <Setter Property="BarBackgroundColor"
                        Value="{DynamicResource Key=navbarcolor}" />
            </Style>
        </ResourceDictionary>
    </Application.Resources>
</Application>

Then modify in changeBackground method :

App.Current.Resources["navbarcolor"] = Color.Red;

If defined color key in App.xaml , also can do as follow :

App.Current.Resources["navbarcolor"] = App.Current.Resources["navbarredcolor"];
Junior Jiang
  • 12,430
  • 1
  • 10
  • 30