0

I'm trying to bind element by name to MenuItem in ContextMenu. Element to binding:

<UserControl x:Class="ATCheckerView.TestsPropagate"
         x:Name="TestPropagateRoot" ...

Working version:

        <HierarchicalDataTemplate x:Key="SchemTemplate">
            <Button Command="{Binding ElementName=TestPropagateRoot, Path=DataContext.vclient.OpenInViewer}" />               
        </HierarchicalDataTemplate>

Non-working:

           <HierarchicalDataTemplate x:Key="SchemTemplate">                
            <TextBlock Text="{Binding path}">
                <TextBlock.ContextMenu>
                    <ContextMenu>
                        <MenuItem Header="{Binding ElementName=TestPropagateRoot}"
                                  Command="{Binding ElementName=TestPropagateRoot, Path=DataContext.vclient.OpenInViewer}"
                                  CommandParameter="{Binding}" />
                    </ContextMenu>
                </TextBlock.ContextMenu>
            </TextBlock>
        </HierarchicalDataTemplate>
RomanKovalev
  • 852
  • 3
  • 10
  • 29

2 Answers2

1

here is a similar question and a good answer which show some ways how to handle contextmenu binding.

btw is use PlacementTarget Binding most time, e.g.

        <TextBlock Text="{Binding path}">
            <TextBlock.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Test"
                              Command="{Binding Path=PlacementTarget.DataContext.vclient.OpenInViewer, 
                                                RelativeSource={RelativeSource AncestorType=ContextMenu}}"
                              CommandParameter="{Binding}" />
                </ContextMenu>
            </TextBlock.ContextMenu>
        </TextBlock>

EDIT: {x:Reference TestPropagateRoot} may also an option if you using .net4.0

Community
  • 1
  • 1
blindmeis
  • 22,175
  • 7
  • 55
  • 74
  • DataContext of TextBlock and ContextMenu and MenuItem initially the same. So your Command's binding does not make sense. – RomanKovalev Aug 07 '12 at 14:10
0

My solution is:

<HierarchicalDataTemplate x:Key="SchemTemplate">
            <TextBlock Text="{Binding path}" 
                       Tag="{Binding DataContext, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:TestsPropagate}}}">
                <TextBlock.ContextMenu>
                    <ContextMenu>
                        <MenuItem Header="Открыть для просмотра"
                                  Command="{Binding Path=PlacementTarget.Tag.vclient.OpenInViewer, 
                            RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}"
                                  CommandParameter="{Binding}" />                                    
                    </ContextMenu>
                </TextBlock.ContextMenu>
            </TextBlock>
 </HierarchicalDataTemplate>
RomanKovalev
  • 852
  • 3
  • 10
  • 29