首页 > 解决方案 > 如何以编程方式从 AppShell 为 MenuItem 设置 StyleClass

问题描述

我想在 AppShell 中创建自己的 MenuItems,这对我有用,但现在我想将 StyleClass 添加到这个 MenuItems。我在 AppShell 中有一个用于 MenuItems 的 StylClass 资源。如果我在 AppShell.xaml 中添加一个 MenuItem,我可以毫无问题地使用它,但我的问题是,如何在代码绑定中创建 MenuItems。

AppShell.xaml

<Shell.Resources>
            <ResourceDictionary>
                <Style Class="MenuItemLayoutStyle" TargetType="Layout" ApplyToDerivedTypes="True">
                    <Setter Property="VisualStateManager.VisualStateGroups">
                        <VisualStateGroupList>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Normal">
                                    <VisualState.Setters>
                                        <Setter TargetName="FlyoutItemLabel" Property="Label.TextColor" Value="{StaticResource Primary}" />
                                    </VisualState.Setters>
                                </VisualState>
                            </VisualStateGroup>
                        </VisualStateGroupList>
                    </Setter>
                </Style>
            </ResourceDictionary>
</Shell.Resources>

AppShell.xaml.cs

private static MenuItem CreateMenuItem(string title, ICommand cmd)
        {
            var menuItem = new MenuItem
            {
                Text = title,
                Command = cmd,
                //Set StyleClass here
                
            };
            return menuItem;
        }

如何在后面的代码中使用 Sheel.Resources 中的 StyleClass?

谢谢你的帮助

标签: c#xamarin.forms

解决方案


首先,为 Menuitem 定义一种样式,如下所示:

<Style Class="menuitemstyle" TargetType="Label">
        <Setter Property="TextColor" Value="Red" />
        <Setter Property="HeightRequest" Value="100" />
    </Style>

然后在 AppShell.cs 中通过代码添加一个 MenuItem,并使用 Shell.Resources 中的样式。

 public AppShell()
    {
        InitializeComponent();

        Items.Add(new MenuItem() { Text="test 1",StyleClass=new[] { "menuitemstyle" } });

         
    }

最后,你可以得到截图:

在此处输入图像描述


推荐阅读