Search code examples
c#wpfmenumahapps.metroprogrammatically-created

Add MahApps.Metro Context Menu programmatically


since I am loading dynamic content into a StackPanel I would like to add a ContextMenu on each Object.

Right now I am doing it with System.Windows.Controls.ContextMenu and it's working.

Unfortunately the Menu looks like in an old Window form and not like the nice Menu of MahApps.

On the Internet page can I find the documentation how to add a menue in xaml, but not how to create a Menu via code.

Do you have any ideas?

Thanks for your help :)


Solution

  • Looking up in MahApps.Metro I found that ContextMenu's Style has the Key MetroContextMenu.

    So you just can create your normal ContextMenu in CodeBehind. The you could add the following Style to your App.xaml

    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <!--  MahApps.Metro resource dictionaries. Make sure that all file names are Case Sensitive!  -->
                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.ContextMenu.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />
                <!--  Accent and AppTheme setting  -->
                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Green.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
        <!-- Apply MetroStyle for ContextMenu to ContextMenus in Application scope -->
        <Style TargetType="ContextMenu" BasedOn="{StaticResource MetroContextMenu}" />
    </Application.Resources>
    

    It is only the you have to apply to your ContextMenu. There is no special ContextMenu control provided by MahApps (it is only the Style!).