Working with the WPF HeaderStringFormat Menu and Access Keys Incidentally

Good. Therefore, I want my application to display the "Save" and "Save As ..." elements in its main menu, as Visual Studio does; that is, "Save {current file}" and "Save {current file} How ..."

I would also like to have regular access keys ("S" and "A" respectively).

I came up with two solutions, but not very desirable.

  • Instead of creating the main menu exclusively in xaml, I could create all of this in MainWindowViewModel so that I can fully control what happens to the created MenuItems. However, I believe that this would be a violation of MVVM (which I am trying to observe very strictly this time), since I would have to include links to each MenuItem icon in the ViewModel. Plus it seems a little dirty.

  • I can specify the title of only these two specific MenuItems (and possibly future ones) like this, but then I get a MenuItem that has not only an underscore in the title, but also does not contain an access key.

<MenuItem Header="{Binding CurrentFileName}" HeaderStringFormat="Save {0} _As..."> 

What should I do?

+4
source share
1 answer

Whelp, figured it out. At least, how to do this with all the main menus described in XAML. Just made the contents of the header an AccessText control instead of a string and 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> 
+4
source

All Articles