[英]Using underscores in WPF menu items when binding
I've created a Recent Files menu item to which I bind a collection of recent file view models. 我创建了“最近文件”菜单项,将最近文件视图模型的集合绑定到该菜单项。
<MenuItem Header="_Recent Files" ItemsSource="{Binding RecentFiles}" Command="{x:Static pm:MainWindow.RecentFileListCommand}">
<MenuItem.ItemContainerStyle>
<Style>
<Setter Property="MenuItem.Header" Value="{Binding}"/>
<Setter Property="MenuItem.Command" Value="{x:Static pm:MainWindow.RecentFileOpenCommand}"/>
<Setter Property="MenuItem.CommandParameter" Value="{Binding FilePath}"/>
</Style>
</MenuItem.ItemContainerStyle>
</MenuItem>
I want the list numbered, and I want the numbers to be used as the shortcut (exactly how Visual Studio does it). 我希望列表编号,并且希望数字用作快捷方式(正是Visual Studio做到的方式)。 My view models have a Number field and Name field.
我的视图模型有一个数字字段和名称字段。 I override the ToString() method to return a header including the underscore:
我重写ToString()方法以返回包含下划线的标头:
return string.Format("_{0} {1}", Number, FilePath);
However, when bound, the underscore is seen as a literal and displays as part of the header text (not the shortcut). 但是,绑定后,下划线被视为文字,并显示为标题文本的一部分(而不是快捷方式)。 I also tried using HeaderStringFormat without luck:How can I get WPF to see the underscore as the shortcut and not a literal string?
我也尝试使用HeaderStringFormat时没有运气:如何让WPF将下划线视为快捷方式而不是文字字符串?
Could try to return an AccessText
, though it might break separation of concerns. 可以尝试返回一个
AccessText
,尽管它可能会中断关注点的分离。
As mentioned by Matthew Whited , a cleaner way would be to return the string only and use a converter to turn it into an AccessText
. 正如Matthew Whited提到的,一种更干净的方法是仅返回字符串,并使用转换器将其转换为
AccessText
。 Alternatively use the HeaderTemplate
and create it there. 或者使用
HeaderTemplate
并在此处创建它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.