16 xamarin.ios xamarin xamarin.forms
我有一个Xamarin Forms
应用程序,我目前正在研究iOS的代码.在我的设置中,我可以选择更改应用程序的主题(黑暗和光明).这基本上只是改变页面的背景颜色和文本颜色.现在我想做的是能够改变SelectedImageTintColor
和BarTintColor
的TabBar
还有中BarTintColor
和TintColor
的NavigationBar
.目前我已经为选项卡页面创建了一个渲染器:
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
App.theme = (Theme)App.DB.GetIntSetting("ThemeColor");
switch (App.theme)
{
case Theme.Dark:
{
TabBar.SelectedImageTintColor = UIColor.FromRGB(255, 165, 0);
TabBar.BarTintColor = UIColor.Black;
break;
}
case Theme.Light:
{
TabBar.SelectedImageTintColor = UIColor.FromRGB(60, 132, 60);
TabBar.BarTintColor = UIColor.White;
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在这些颜色只有在您第一次启动应用程序时才会生效.
我研究了这个问题,但没有找到任何人如何解决这个问题的答案.
我知道Xamarin已经有很多变化,所以我想知道是否有最近的发展或新的方法来解决这个问题.我愿意研究任何可能的建议,因为应用程序的要求的一部分是能够改变这些颜色.
编辑:
我的Tabbed
页面创建如下:
public partial class MainPage : TabbedPage
{
public MainPage()
{
InitializeComponent();
var phrasesPage = new NavigationPage(new PhrasesPage())
{
Title = "Play",
Icon = "play1.png"
};
var settingsPage = new NavigationPage(new SettingsPage())
{
Title = "Settings",
Icon = "settings.png"
};
// other declarations here
Children.Add(phrasesPage);
Children.Add(settingsPage);
// and more
}
}
Run Code Online (Sandbox Code Playgroud)
举例来说,如果让我选择深色主题则TabBar
和NavigationBar
背景颜色将是黑的,TabBar
的selectedimage将是橙色,NavigationBar
的文字是白色的.同样,如果我选择了浅主题则TabBar
和NavigationBar
背景颜色将是白色的,TabBar
的selectedimage将是绿色和NavigationBar
的文本将是黑色的.
小智 8
我认为问题在于你没有倾听和处理主题变化.您正在设置OnElementChanged
更改主题时不会再次调用的颜色.
您可以创建一个属性,该属性将触发您在自定义渲染器中订阅的事件.例如,如果您在App类中创建属性,则可以在自定义TabbedPage渲染器中执行以下操作:
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if(e.OldElement != null)
{
App.Current.PropertyChanged -= Current_PropertyChanged;
return;
}
App.Current.PropertyChanged += Current_PropertyChanged; //subscribe to the App class' built in property changed event
UpdateTheme();
}
void Current_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if(e.PropertyName == "DarkTheme")
{
UpdateTheme();
}
}
Run Code Online (Sandbox Code Playgroud)
由于导航栏由NavigationPage控制,因此您还必须在那里监听属性更改.幸运的是,您不需要自定义渲染器,因为您可以使用Forms属性更改条形和文本颜色.因此,您可以创建一个继承自NavigationPage并订阅该事件的类:
public class CustomNavigationPage : NavigationPage
{
public CustomNavigationPage(Page root) : base(root)
{
if(Device.OS == TargetPlatform.iOS)
{
App.Current.PropertyChanged += Current_PropertyChanged;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我创建了一个示例项目,演示了所有这些,所以你可以看看:)
归档时间: |
|
查看次数: |
5748 次 |
最近记录: |