0

I currently trying to create a dynamically created context menu. I'm currently binding a ObservableCollection<MenuItem> to the ItemsSource property on the context menu. I now want to set the visibility of the items in the list when the menu opens depending on what I have selected.
I tried Inheriting from MenuItem like this

public class CtContextMenuItem : MenuItem
{
    public delegate Visibility VisibilityDelegate();
    public VisibilityDelegate IsVisibleDelegate = null;
}

And I want to set Visibility to the result of the VisibilityDelegate when the context menu is opened but I can't find any event or method that is called on the MenuItem when the context menu is opened
Is there a way to do it or is it do I have to just create all the items of the menu inside a function listening to ContextMenuOpening?

Hampus
  • 137
  • 2
  • 14
  • *"listening to ContextMenuOpening"* - yes. Enumerate menu items and call that delegate either directly or via property (if data template binding is used). Consider to add a little of [mvvm](https://stackoverflow.com/q/15566824/1997232) instead of using custom controls. – Sinatr Oct 10 '17 at 09:17

1 Answers1

0

Bind the ItemsSource to an ObservableCollection<CtContextMenuItem> where the CtContextMenuItem type has a Visibility or bool property that you can bind to in your XAML. Something like this:

public class CtContextMenuItem
{
    public Visibility IsVisible { get; set; }
}

<ContextMenu ItemsSource="{Binding TheSourceCollection}">
    <ContextMenu.ItemContainerStyle>
        <Style TargetType="MenuItem">
            <Setter Property="Visibility" Value="{Binding IsVisible}" />
        </Style>
    </ContextMenu.ItemContainerStyle>
</ContextMenu>
mm8
  • 163,881
  • 10
  • 57
  • 88