WPF: Menu Items only bind command parameters once

前端 未结 1 459
我在风中等你
我在风中等你 2020-12-18 12:24

Ive noticed this a couple of times when using menus with commands, they are not very dynamic, check this out. I am creating a menu from a collection of colours, I use it to

相关标签:
1条回答
  • 2020-12-18 13:04

    The problem is that ContextMenu's are apparently the root of their own visual tree I read somewhere that it takes the datacontext its parent, but only once on loading, so if the parents datacontext changes the menuitems does not. (unfortunately I can't find a link for that right not)

    I have encountered this problem before, and what I did was use Josh Smith's Virtual Branch Pattern. It's fairly technical but the article helped me understand really well what was going on with this visual tree nonsense.

    Essentially you create this bridge that binds to the view's datacontext. The bridge is created as a static resource, allowing you to bind to it from the context menu even if it is outside the visual tree.

    Add this to your xaml:

    <Window.Resources>
       <!-- This is the "root node" in the virtual branch
       attached to the logical tree. It has its
       DataContext set by the Binding applied to the
       Window's DataContext property. -->
       <FrameworkElement x:Key="DataContextBridge" />
    </Window.Resources>
    
    <Window.DataContext>
       <!-- This Binding sets the DataContext on the "root node"
       of the virtual logical tree branch.  This Binding
       must be applied to the DataContext of the element
       which is actually assigned the data context value. -->
       <Binding
        Mode="OneWayToSource"
        Path="DataContext"
        Source="{StaticResource DataContextBridge}"
       />
    </Window.DataContext>
    

    This is the bridge I spoke of. It takes the datacontext and __pushes it_ to to the bridges datacontext, which is (as I said before) a static resource.

    Then you simply this to the contextmenu's datacontext:

     DataContext="{Binding
                   Source={StaticResource DataContextBridge},
                   Path=DataContext}"
    

    Now throw away all the relative pathing etc and use regular binding inside the menu items, and you should be fine. The datacontext will update as usual.

    Just one note:

    You will obviously have to have some property in the datacontext to discern which command to use, but i'm sure you can figure it out. This solution just deals with the way contextmenu's dont update

    0 讨论(0)
提交回复
热议问题