当 UI 元素绑定到命令时,如何使用 StringFormat 去除 InputGesture 文本?

How do I use StringFormat to get rid of the InputGesture text when a UI element is bound to a command?

我有一个绑定到字符串集合的菜单项列表。单击这些菜单项中的每一个时,都会触发我的“打开”命令。这一切都很好。

如何省略每个菜单项旁边的 Ctrl+O?

下面是我的XAML.

                <MenuItem Header="Recent packages" ItemsSource="{Binding Source={x:Static p:Settings.Default}, Path=RecentItems}">
                <MenuItem.ItemTemplate>
                    <DataTemplate>
                        <MenuItem CommandTarget="{Binding}" Command="ApplicationCommands.Open" CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Header}">
                        <MenuItem.Header>
                                <TextBlock>
                                    <TextBlock.Text>
                                        <Binding StringFormat="{}{0}" />
                                    </TextBlock.Text>
                                </TextBlock>
                            </MenuItem.Header>
                        </MenuItem>
                    </DataTemplate>
                </MenuItem.ItemTemplate>
            </MenuItem>

这是我正在谈论的图片。

How do I use StringFormat to get rid of the InputGesture text when a UI element is bound to a command?

你不知道。 Header 属性 与手势文本的显示无关,应用 StringFormat 或其他任何内容都不会产生任何效果。

您可以使用 Hide or disable Input Gesture Text in wpf, suggested by 中的方法。在这种情况下,您可能只需将文本颜色的 alpha 设置为 0。但更简单的方法是将 MenuItem.InputGestureText 值设置为 " "(注意 space…如果您使用空字符串,WPF 将忽略它)。

综上所述,我认为您的处理方式有误。

您首先获得手势文本的原因是因为您使用 ApplicationCommands.Open 作为菜单项的命令。但这并不是真正正确的命令。您已经将其用于 "File" 菜单中的 "Open package…" 命令。所以这不是同一个命令,是吗?

即使您隐藏输入手势文本,实际上也不会删除 手势。它只是没有在菜单中记录它。那么,当用户按下Ctrl+O时,您希望执行这三个菜单项中的哪一个?您如何期望 WPF 确定它会执行您想要的命令?

在我看来,您应该定义自己的 ICommand 以与这些菜单项一起使用,而不要使用 ApplicationsCommand.Open 命令。为您确实需要键盘快捷键的一个命令保留它。使用您自己的 ICommand(例如 RoutedUICommand),您可以简单地不定义输入 gesture/keyboard 快捷方式,然后菜单中将不会显示任何内容。