如何获取导航栏背景颜色?

时间:2018-05-14 18:06:13

标签: xamarin.forms

在我的Xamarin.Forms应用程序中,我希望我的Grid背景颜色与导航栏的背景颜色相同,如下所示:

BackgroundColor="{StaticResource BarBackgroundColor}"

我该怎么做?

3 个答案:

答案 0 :(得分:3)

您可以通过将当前页面转换为导航页面来检索导航栏的颜色。然后,您只需使用检索到的颜色更改网格的颜色即可。在页面的OnAppearing覆盖上,使用以下代码获取导航栏颜色:

protected override void OnAppearing()
{
   var navPage = Application.Current.MainPage as NavigationPage;
   if (navPage != null)
   {
      var barColor = navPage.BarBackgroundColor;
   }
   base.OnAppearing();
}

或者,如前所述,您可以在App.xaml中预定义颜色,然后从那里简单地使用它。

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

答案 1 :(得分:0)

BarBackgroundProperty是来自NavigationPage的附加属性。请注意,它可以在您推送到NavigationPage的每个页面上更改。

假设你有一个像这样设置的App.Current.MainPage:

Page main = new MainPage();
Page navigation = new NavigationPage(main)
{
    BarBackgroundColor = Color.Red,
    BarTextColor = Color.Yellow
};

navigation页面是拥有BarBackgroundColor属性的页面。所以如果你想要检索它,你应该从那里得到它。我无法通过StaticResource了解如何获得此信息。

我猜您可以通过viewmodel上的属性实现此目的。例如:

public class MyViewModel
{
    ...
    public Color BarBackgroundColor
    {
        get
        {
            return ((NavigationPage)App.Current.MainPage)?.BarBackgroundColor;
        }
    }
    ...
}

并在您的XAML上使用它(一旦MyViewModel {或其继承}是BindingContext或您的页面):

BackgroundColor="{Binding BarBackgroundColor}"

我希望它有所帮助。

答案 2 :(得分:0)

您可以将下面的代码放入App.xaml

中来使用全局样式
<Application.Resources>
        <ResourceDictionary>
            <Color x:Key="NavigationPrimary">#1A237E</Color>
            <Style TargetType="NavigationPage">
                <Setter Property="BarBackgroundColor" Value="{StaticResource NavigationPrimary}" />
                <Setter Property="BarTextColor" Value="White" />
            </Style>
            <Style TargetType="Grid">
               <Setter Property="BackgroundColor" Value="{StaticResource NavigationPrimary}" />
            </Style>
        </ResourceDictionary>
    </Application.Resources>