繁体   English   中英

是否可以在Xamarin Forms Android中动态更改标签栏选定的项目颜色?

[英]Is it possible to change the tabbar selected item color dynamically in Xamarin Forms Android?

我有一个Xamarin Forms应用程序,它为用户提供了3个主题选项。 我希望能够通过单击按钮更改Tabbar背景,所选项目和未选择的项目颜色。 在iOS中,我可以使用如下的渲染器执行此操作:

protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
    base.OnElementChanged(e);

    if(e.OldElement != null)
    {
        Xamarin.Forms.Application.Current.PropertyChange -= Current_PropertyChanged;
        return;
    }

    Xamarin.Forms.Application.Current.PropertyChange += Current_PropertyChanged; //subscribe to the App class' built in property changed event
    UpdateTheme();
}

void Current_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
    UpdateTheme();
}

在Android中,我知道可以在styles.xml更改这些颜色,但这只允许我设置一次颜色。 另外,我使用ToolbarPlacement="Bottom"将我的标签栏放在屏幕的底部。

android:TabbedPage.ToolbarPlacement="Bottom"
android:TabbedPage.BarSelectedItemColor="Red"
android:TabbedPage.IsSwipePagingEnabled="False"

我想知道是否可以通过单击按钮动态更改BarSelectedItemColor

我终于通过使用DynamicResource样式来实现这一点:

由此:

android:TabbedPage.BarSelectedItemColor="Red"

对此:

android:TabbedPage.BarSelectedItemColor="{DynamicResource BarSelectedItemColor"

您可以查看此链接

这是谈论动态ResourceThem或类似的东西。

<Application>
    xmlns="zamarin schema{forms}"
    xmlns:x="microsoft schema{xaml}"
    x:Class="name">
    <Application.Resources>
        <ResourceDictionary>
            <Color x:Key="backgroundColor">your color</Color>
            <Color x:Key="textColor">name of color</Color>
        </ResourceDictionary>
    </Application.Resources>
</Application>

静态资源

StaticResource标记扩展允许我们引用预定义的资源,但有一个关键限制:字典中的资源仅在控件实例化期间被提取一次,并且不能在runtime更改。 语法与绑定的语法非常相似; 只需将属性的值设置为“{StaticResource Resource_Name}”即可。 让我们更新我们的ViewCell以使用我们定义的资源:

<Label Text="{Binding Name}" FontSize="Medium" FontAttributes = "Bold" TextColor = "{DynamicResource textColor}" LineBreakMode="NoWrap"/>
<Label Text="{Binding Text}" FontSize="Small" LineBreakMode="WordWrap" TextColor = "{DynamicResource textColor}"/>

现在! 在此代码中,您可以更改资源:

App.Current.Resources ["backgroundColor"] = Color.White;
App.Current.Resources ["textColor"] = Color.Black;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM