首页 > 解决方案 > 如何从 Xamarin 表单中的其他页面动态更改 TabbedPage 的 backgroundColor

问题描述

我有一个标签页,如下所示:

主页.xaml

<TabbedPage BackgroundColor="{Binding HomeBgColor}">
    <TabbedPage.Children>
        <local:MainPage/>
     </TabbedPage.Children>
</TabbedPage>

我正在 MainPage 中执行一项操作,我需要在该操作上更改选项卡式页面的背景颜色。

我尝试了以下方法,但似乎不起作用。

public class HomePageViewModel:ViewModelBase
    {
        INavigationService navigationService;

        
        private string homeBgColor = "#FFFFFF"
        public string HomeBgColor
        {
            get
            {
                return homeBgColor;
            }
            set
            {
                homeBgColor = value;
               RaisePropertyChanged("HomeBgColor");
            }
        }

        public HomePageViewModel(INavigationService navigation)
        {

        }
    }

MainPageViewModel.cs

public HomePageViewModel LoginVM { get; private set; }
OnButtonClick()
{
  LoginVM = new HomePageViewModel(navigationService);
  LoginVM.HomeBgColor = "#007AFF";
}

知道出了什么问题吗?
任何帮助表示赞赏!

标签: c#xamarin.forms

解决方案


如果你想改变Tabbar的颜色,你可以使用Custom Renderer

在 iOS 中

[assembly: ExportRenderer(typeof(TabbedPage), typeof(TabbedPageRenderer))]
namespace xxx.iOS
{
    public class TabbedPageRenderer : TabbedRenderer
    {
        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);

            TabBar.TintColor = UIColor.White;
            TabBar.BarTintColor = UIColor.Black;
            TabBar.BackgroundColor = UIColor.Gray;
        }
    }
}

在安卓中

[assembly: ExportRenderer(typeof(TabbedPage), typeof(MyTabbedPageRenderer))]
namespace xxx.Droid
{
    public class MyTabbedPageRenderer : TabbedPageRenderer
    {
        public MyTabbedPageRenderer(Context context) : base(context)
        {

        }

        protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e)
        {
            base.OnElementChanged(e);

            if (e.OldElement == null && e.NewElement != null)
            {
                for (int i = 0; i <= this.ViewGroup.ChildCount - 1; i++)
                {
                    var childView = this.ViewGroup.GetChildAt(i);
                    if (childView is ViewGroup viewGroup)
                    {
                        for (int j = 0; j <= viewGroup.ChildCount - 1; j++)
                        {
                            var childRelativeLayoutView = viewGroup.GetChildAt(j);
                            if (childRelativeLayoutView is BottomNavigationView)
                            {
                                  (BottomNavigationView)childRelativeLayoutView).SetBackgroundColor(Android.Graphics.Color.Green);
                            }
                        }
                    }
                }
            }
        }
    }
}

推荐阅读