Context Menu Binding to Parent Window's Datacontext

后端 未结 2 1948
情深已故
情深已故 2020-12-16 07:10

I have a TreeListControl that binds to a collection in my VM. I also want to define the context menu inside the treelistcontrol having its header text bind to another string

相关标签:
2条回答
  • 2020-12-16 07:58

    Provide a name for your window and explicitly bind to it such as

    <window  x:Name="ReportsPage"/>
    
    ...
    
     <MenuItem DataContext="{Binding ElementName=ReportsPage}"/>
    

    UPDATE

    Since the context menu is actually in its own window, binding is a bit trickier. Hence the best bet is to walk up the RelativeSource to the context's parent and pull the header text from there:

        <Window.DataContext>
            <local:MainVM HeaderText="Jabberwocky" />
        </Window.DataContext>
    
        ...
    
    <TextBlock Text="{Binding HeaderText}">
        <TextBlock.ContextMenu>
            <ContextMenu>
    
    <MenuItem Header="{Binding Path=Parent.DataContext.HeaderText, 
                        RelativeSource={RelativeSource Self}}" />
    
            </ContextMenu>
        </TextBlock.ContextMenu>
    

    Which for this context produces this

    enter image description here

    0 讨论(0)
  • 2020-12-16 08:12

    This binds to a Window:

    DataContext="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
    

    If the command AddItemCommand and property AddItemText are defined on the Window ViewModel, bind to Window DataContext:

    DataContext="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=DataContext}"
    
    0 讨论(0)
提交回复
热议问题