我正在使用 WinUI 3 和 WindowsAppSDK。当我使用 NavigationView 并在 NavigationViewItem 上设置 AccessKey 时,它会起作用……直到我还定义了 MenuItemTemplate。一旦将 DataTemplate 用于 MenuItemTemplate,访问键就会停止工作。关于如何解决这个问题有什么想法吗?
举个例子。有什么想法吗?
<NavigationView>
<NavigationView.MenuItems>
<NavigationViewItem AccessKey="N">Nibble</NavigationViewItem>
<NavigationViewItem AccessKey="P">Pancake</NavigationViewItem>
</NavigationView.MenuItems>
<!-- uncomment this to break the access key functionality
<NavigationView.MenuItemTemplate>
<DataTemplate x:DataType="NavigationViewItem">
<StackPanel>
<ContentPresenter Content="{Binding Icon}" Margin="0,0,8,0"/>
<TextBlock Text="{Binding Content}"/>
</StackPanel>
</DataTemplate>
</NavigationView.MenuItemTemplate>
-->
</NavigationView>
我猜
AccessKey
不起作用,因为原始菜单项 NavigationViewItems
有 AccessKeys
,被 NavigationViewItem
包裹。
相反,此代码将类似于您要实现的目标:
using Microsoft.UI.Xaml.Controls;
using System.Collections.Generic;
namespace WinUI3App;
public class MenuItem
{
public MenuItem(string text, Symbol icon, string accessKey)
{
Text = text;
Icon = icon;
AccessKey = accessKey;
}
public string Text { get; }
public Symbol Icon { get; }
public string AccessKey { get; }
}
public sealed partial class MainPage : Page
{
public List<MenuItem> MenuItems = new()
{
new MenuItem(text: "Nibble", icon: Symbol.Emoji, accessKey: "N"),
new MenuItem(text: "Pancake", icon: Symbol.Emoji2, accessKey: "P"),
};
public MainPage()
{
this.InitializeComponent();
}
}
<Page
x:Class="WinUI3App.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="using:WinUI3App"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
mc:Ignorable="d">
<NavigationView MenuItemsSource="{x:Bind MenuItems, Mode=OneWay}">
<NavigationView.MenuItemTemplate>
<DataTemplate x:DataType="local:MenuItem">
<NavigationViewItem AccessKey="{x:Bind AccessKey}">
<Grid ColumnDefinitions="Auto,*">
<SymbolIcon
Grid.Column="0"
Symbol="{x:Bind Icon, Mode=OneWay}" />
<TextBlock
Grid.Column="1"
Text="{x:Bind Text, Mode=OneWay}" />
</Grid>
</NavigationViewItem>
</DataTemplate>
</NavigationView.MenuItemTemplate>
</NavigationView>
</Page>