如何在WPF中为每个应用程序屏幕设置不同的菜单

时间:2015-02-27 13:26:11

标签: wpf menu

我的应用程序有三个屏幕:Overview,CreateActivity和ViewActivities。

当我在CreateActivity中时,我希望显示一些仅对该屏幕有意义的菜单,同样适用于ViewActivities屏幕,该屏幕还有另一个独家菜单。

这与现在在Microsoft Office中发生的情况类似:您单击某个选项卡,菜单栏中会显示一些与该选项卡相关的额外菜单条目。

我应该如何在WPF中实现它?

目前,我的主窗口如下所示。有一个ActiveScreen类型的属性ViewModelBase,我想将菜单栏内容绑定到我的三个屏幕的每个不同。

<Window
        (...)
        x:Class="CompanyNamespace.Product.Views.ShellView">

    <Window.DataContext>
        <vm:ShellViewModel/>
    </Window.DataContext>

    <DockPanel>
        <Menu DockPanel.Dock="Top">
            <!-- What here? -->
        </Menu>
        <ContentControl Content="{Binding ActiveScreen}"/>
    </DockPanel>

</Window>

1 个答案:

答案 0 :(得分:1)

我的建议是更改每个Menu / MenuItem的可见性。

首先使用flags属性创建一个枚举。我可以添加一个项All = 7,但在这种情况下,没有必要这样做。而只是从XAML中的Visibility="..."中删除MenuItem部分

[Flags]
public enum MenuSetTypes
{
    //I prefer adding a None in flags mode
    None = 0,

    //main items
    Overview = 1,
    CreateActivity = 2,
    ViewActivities = 4,

    //define multi state items
    OverviewAndCreate = 3,
    CreateAndView = 6,
}

添加可绑定属性以查看模型

public MenuSetTypes MenuSetType { ... } 

MenuItem XAML:

<MenuItem Header="SomeMenuVisibileInOverViewAndCreate"
          Visibility="{Binding ActiveScreen.MenuSetType,
          Converter={StaticResource MenuTypeToVisibilityConverter},
          ConverterParameter={x:Static enums:MenuSetTypes.OverviewAndCreate}}"/>

转换器代码:

public class MenuTypeToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        //value & param highlights enum items that are in both value and param
        //so that by comparing it with None we can tell if there is any
        //overlapped enum item or not 
        return ((MenuSetTypes)value & (MenuSetTypes)parameter) == MenuSetTypes.None ?
             Visibility.Collapsed : Visibility.Visible;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}