dimanche 28 juin 2015

WPF Build ContextMenu dynamically via MVVM

I have a TreeView where I display items bound via the TreeViews HierarchicalDataTemplate.ItemsSource. The context-menu of the TreeView changes based on which item is selected. The menu-items depend on the selected item. This means: the context-menu is built completely dynamic. For this purpose I wrote a MenuItemModel class, that serves as the business-object for a menu item. Like this:

public class MenuItemModel : ViewModelBase
{
  public string Header { get; set; }
  public string Icon { get; set; }
  public ObservableCollection<MenuItemModel> ChildItems { get; set; }
  public UiCommand Command { get; set; }
}

So far so good. But now I have two questions:

Question 1 How can I display a separator in the menu? I have another class SeparatorMenuItemModel that I planned to use for separators. But in that case my ContextMenu needs to contain a Separator and not a MenuItem. How can I do that?

Question 2 I tried to use a DataTemplate to customize how my MenuItems are displayed. But that does not change the menu itself, just the content-part. I'd have to use a ControlTemplate for that, but how can I make my Menu change ControlTemplate the way I could do with DataTemplate?

Aucun commentaire:

Enregistrer un commentaire