问题
Okay. So I want my application to display in its main menu the "Save" and "Save As..." items just like Visual Studio does; i.e. "Save {current file}" and "Save {current file} As..."
I would also like to have the normal access keys ("S" and "A", respectively).
I've come up with two solutions, but neither is very desirable.
Instead of creating the main menu exclusively in xaml, I could create it all in the MainWindowViewModel so I'd have full control over what goes into the generated MenuItems. However, I feel that this would be a violation of MVVM (which I'm attempting to abide by very strictly this time around) as I would have to include references to each MenuItem's Icon in the ViewModel. Plus it seems a little messy.
I can stipulate the header of just these two specific MenuItems (and perhaps future ones) like so, but then I end up getting a MenuItem that not only has a underscore in the header, but also does not contain an access key.
<MenuItem Header="{Binding CurrentFileName}"
HeaderStringFormat="Save {0} _As...">
What should I do?
回答1:
Whelp, figured it out. At least about how to get it done with the whole main menu described in XAML. Just made the header content an AccessText control instead of a string and it works like a charm.
<MenuItem>
<MenuItem.Style>
<Style TargetType="{x:Type MenuItem}">
<Style.Triggers>
<DataTrigger Binding="{Binding HasSelection}" Value="false">
<Setter Property="IsEnabled" Value="false"/>
<Setter Property="Header">
<Setter.Value>
<AccessText Text="Save Selected File _As..."/>
</Setter.Value>
</Setter>
</DataTrigger>
<DataTrigger Binding="{Binding HasSelection}" Value="true">
<Setter Property="IsEnabled" Value="true"/>
<Setter Property="Header">
<Setter.Value>
<AccessText Text="{Binding SelectedFile.Filename, StringFormat=Save {0} _As...}"/>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</MenuItem.Style>
</MenuItem>
来源:https://stackoverflow.com/questions/11313037/dealing-with-wpf-menu-headerstringformat-and-access-keys-among-other-things