如何在内容页中更改标签栏的背景颜色?
我正在用C#在 MAUI应用中实现一个功能:可以改变按钮的颜色。同时,我希望在更新按钮颜色时,能够同步改变选项卡栏的背景颜色。
我在AppShell.xaml中使用
在AppShell.xaml中有一个名为buttoncolor的可绑定属性。如何在AppShell的某个内容页中,通过AppShell的
AppShell.xaml
<?xml version="1.0" encoding="UTF-8" ?>
<Shell
x:Class="SleepDiary.AppShell"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:SleepDiary"
Shell.FlyoutBehavior="Disabled"
Shell.TabBarTitleColor="{Binding buttontextcolor}"
Shell.TabBarUnselectedColor="LightGray"
Shell.TabBarBackgroundColor="{Binding buttoncolor}">
第一种方案
在我的内容页中,我尝试调用:
AppShell.SetTabBarBackgroundColor(this, Colors.Purple);
我不是一个很会编程的人,但我理解上一行不应该使用this。不过,我不知道如何定义一个与AppShell相连的BindableObject。
第二种方案
我也尝试在AppShell中创建一个可以从内容页调用的方法。这里遇到了两个问题:要么把它设为static;但那样就无法在AppShell中使用buttoncolor。
public static void SetTabBarColor(Color color)
{
buttoncolor = color;
}
如果去掉static,我可以设置buttoncolor;但另一方面,我却无法从内容页调用SetTabBarColor。
public void SetTabBarColor(Color color)
{
buttoncolor = color;
}
我在内容页调用该方法时,使用下面这行代码会报错:
AppShell.SetTabBarColor(Colors.Purple);
我也有一个想法,使用下面的代码,但与上面关于static/非static的困难相同:
public void SetTabBarColor(Color color)
{
AppShell.SetTabBarBackgroundColor(this, color);
}
如果有人有解决这个问题的思路,我们将不胜感激!
我没有视图模型,也不是一个很擅长编程的人。我曾考虑实现一个视图模型,但我认为对我的技能来说太复杂了。因此如果有一种不需要视图模型的解决方案,我会更倾向于那种。
先行致谢!
/Niklas
解决方案
你有没有考虑过DynamicResources?
在Colors.xaml中:
<Color x:Key="TabBarBackgroundColor">Purple</Color>
在AppShell.xaml中:
Shell.TabBarBackgroundColor="{DynamicResource TabBarBackgroundColor}"
在C#中,将该颜色改为Red:
Application.Current.Resources["TabBarBackgroundColor"] = Colors.Red;
另请参阅:
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。