【问题标题】:Xamarin switching control's themeXamarin 切换控件的主题
【发布时间】:2022-01-03 18:05:45
【问题描述】:

我想做的只是在单击按钮时使用 c# 更改按钮的主题。

我在 xaml 中有什么:

BackgroundColor="{x:AppThemeBinding Light={StaticResource Body_Default_Background}, Dark={StaticResource Body_Default_Background_Dark}}"

我想用c#设置App主题绑定

我试过了:

button.BackgroundColor = "{x:AppThemeBinding Light={StaticResource Body_Default_Background}, Dark={StaticResource Body_Default_Background_Dark}}"

【问题讨论】:

    标签: c# xamarin xamarin.android xamarin.ios


    【解决方案1】:

    单击按钮时更改按钮的主题

    您可以使用VisualStateManagerEventTrigger 简单地更改按钮的BackgroundColor

    可以参考以下代码:

    <Button Text="Click Me!">
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
                <VisualState x:Name="Normal">
                    <VisualState.Setters>
                        <Setter Property="BackgroundColor" Value="Green" />
                    </VisualState.Setters>
                </VisualState>
                <VisualState x:Name="Pressed">
                    <VisualState.Setters>
                        <Setter Property="BackgroundColor" Value="Red" />
                    </VisualState.Setters>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
    </Button>
    

    或者使用EventTrigger来实现这个:

    创建ButtonTriggerAction.cs

    public class ButtonTriggerAction : TriggerAction<VisualElement>
    {
        public Color BackgroundColor { get; set; }
    
        protected override void Invoke(VisualElement visual)
        {
            var button = visual as Button;
            if (button == null) return;
            if (BackgroundColor != null) button.BackgroundColor = BackgroundColor;
        }
    }
    

    及用法:

    <Button Text="using EventTrigger">
        <Button.Triggers>
            <EventTrigger Event="Pressed">
                <local:ButtonTriggerAction BackgroundColor="Red" />
            </EventTrigger>
            <EventTrigger Event="Released">
                <local:ButtonTriggerAction BackgroundColor="Default" />
            </EventTrigger>
        </Button.Triggers>
    </Button>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      • 2021-09-10
      • 2021-12-31
      • 2022-09-30
      • 1970-01-01
      • 2021-08-12
      • 2018-09-21
      相关资源
      最近更新 更多