c# - 如何以编程方式从 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?
谢谢你的帮助
解决方案
首先,为 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" } });
}
最后,你可以得到截图:
推荐阅读
- angular - 为什么对话框在页面左侧部分打开?
- javascript - JavaScript 多选 - Vue.js
- sql-server - 动态分区值 SQL Server Azure Synapse
- maven - 在 jenkins 中运行所有 maven 测试用例
- android - 如何使用导航组件将数据从适配器类发送到片段
- python - 将字典从 csv 列读入数据框
- python - 如何使用 SQL 查询或 Python 转换作为多分类响应变量的字符串
- python - 为什么在排序值时会出现 SettinWithCopyError?
- sql - 如何在Oracle中将列列为行
- c++ - 链接器标志 -Wl,--exclude-libs,ALL 在所有情况下都不起作用