Dealing with WPF Menu HeaderStringFormat and Access Keys among other things

为君一笑 提交于 2019-12-23 11:57:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!