如何在 Windows.Controls.ContextMenu 菜单项中右对齐加速器文本?
在 Win32 API 中,制表符 (\t
) 用于在菜单项 ("Open\tCtrl+O"< /代码>)。在 C# 应用程序中,我有一个从 System.Windows.Controls.ContextMenu 派生的类,并且以类似的方式使用制表符似乎无法达到相同的结果;它实际上插入了一个制表符,因此快捷方式看起来更居中对齐而不是右对齐。
我知道在 .net 中 _
用于代替 Win32 &
作为助记符下划线。 \t
有类似的替代品吗?
编辑:上下文代码(没有 ICommand 实现)
internal class MyContextMenu : ContextMenu, ICommand
{
private readonly string[] wordList;
public MyContextMenu(string aWord)
{
var itemStyle = (Style) TryFindResource("EditorContextMenuItem");
wordList = GetMyWordList(aWord);
if (wordList != null)
{
for (int i = 0; i < wordList.Length; ++i)
{
string word = wordList[i];
var item = new MenuItem
{
Style = itemStyle,
Header = BuildMenuText(i + 1, word),
Command = this,
CommandParameter = i
};
this.Items.Add(item);
}
}
}
static private string BuildMenuText(int index, string text)
{
string menuText;
if (index > 0 && index < 16)
menuText = text + "\t_" + index.ToString("x");
else
menuText = "_" + text;
return menuText;
}
}
In the Win32 API, the tab character (\t
) is used to display right-aligned text (like for accelerators / shortcuts) in a menu item ("Open\tCtrl+O"
). In a C# app, I have a class derived from System.Windows.Controls.ContextMenu
and it appears that using the tab character in a similar manner does not achieve the same result; it actually inserts a tab, so the shortcut looks more center-aligned than right-aligned.
I know that in .net _
is used in place of the Win32 &
for mnemonic underlines. Is there a similar substitute for \t
?
Edit: code for context (without the ICommand implementation)
internal class MyContextMenu : ContextMenu, ICommand
{
private readonly string[] wordList;
public MyContextMenu(string aWord)
{
var itemStyle = (Style) TryFindResource("EditorContextMenuItem");
wordList = GetMyWordList(aWord);
if (wordList != null)
{
for (int i = 0; i < wordList.Length; ++i)
{
string word = wordList[i];
var item = new MenuItem
{
Style = itemStyle,
Header = BuildMenuText(i + 1, word),
Command = this,
CommandParameter = i
};
this.Items.Add(item);
}
}
}
static private string BuildMenuText(int index, string text)
{
string menuText;
if (index > 0 && index < 16)
menuText = text + "\t_" + index.ToString("x");
else
menuText = "_" + text;
return menuText;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将加速器文本设置为 MenuItem.InputGestureText 财产。
另外,请注意文档页面中的注释:此属性不会将输入手势与菜单项关联起来;它只是将文本添加到菜单项。应用程序必须处理用户的输入才能执行操作。有关如何将命令与菜单项关联的信息,请参阅命令。
Set your accelerator text to the MenuItem.InputGestureText property.
Also, note the remark in the documentation page: This property does not associate the input gesture with the menu item; it simply adds text to the menu item. The application must handle the user's input to carry out the action. For information on how to associate a command with a menu item, see Command.