WPF Dynamic Context Menu with Caliburn.Micro

末鹿安然 提交于 2019-12-08 10:24:45

问题


I am trying to create a dynamic context menu in my Caliburn.Micro based application. Can anyone share an example of an effective way to do that? So far, I have a very minimal model for each context menu item:

public class ContextMenuUiModel
{
    public string Name { get; set; }
}

a property in my view model that presents a list of those menu item models:

      BindableCollection<ContextMenuUiModel> m_ContextMenuItems = new BindableCollection<ContextMenuUiModel>
  {
     new ContextMenuUiModel { Name="Item 1"},
     new ContextMenuUiModel { Name="Item 2"},
     new ContextMenuUiModel { Name="Item 3"}
  };
  public BindableCollection<ContextMenuUiModel> ContextMenuItems
  {
     get {return m_ContextMenuItems;}
  }

and, a menu item named for the collection property (based on the menu creation in FreePIE, found via this question and answer)

         <TreeView  x:Name="ConfigItemTree" VerticalAlignment="Top" ItemsSource="{Binding ConfigTreeRoot}" >
           <TreeView.ContextMenu>
             <ContextMenu >
                <MenuItem x:Name="ContextMenuItems" DisplayMemberPath="Name" />
             </ContextMenu>
         </TreeView.ContextMenu>

Caliburn.Micro logging reports "No actionable element for get_ContextMenuItems". Also, although Caliburn is noting other named elements for which no property was found (e.g. "Binding Convention Not Applied: Element ConfigItemTree did not match a property."), it is not making a similar statement for ContextMenuItems. So, it seems Caliburn is just not seeing the ContextMenu as an element it could or should deal with.

Maybe the issue is that Caliburn can't see the context menu because it doesn't actually exist until a right click happens (similar to this issue with collapsed elements)?

Ultimately, I would like the context menu's contents to be based on the tree view item that was right clicked, possibly including sub menus and/or disabled items. For a start, though, I'll settle for whatever items I can get.


回答1:


Bind the ItemsSource property of the ContextMenu to the ContextMenuItems property:

<ContextMenu ItemsSource="{Binding PlacementTarget.DataContext.ContextMenuItems, RelativeSource={RelativeSource Self}}" 
             DisplayMemberPath="Name" />


来源:https://stackoverflow.com/questions/53396484/wpf-dynamic-context-menu-with-caliburn-micro

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