How do I get to the WPF element containing the ContextMenu?

Tell me how to get a link in the event handler (for example, Click) ContextMenu to the interface element to which ContextMenu is bound. Example of markup`

<TextBlock Text="123">
    <TextBlock.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Копировать" Click="MenuItem_Click_1"/>
        </ContextMenu>
    </TextBlock.ContextMenu>
</TextBlock>

In the event handler, I want to get, for example, TextBlock. Text.

private void MenuItem_Click_1(object sender, RoutedEventArgs e)
{
    //TextBlock tbl = (TextBlock) SOMETHING???;
    //MessageBox.Show(tbl.Text);
}
 2
Author: Андрей NOP, 2018-03-29

1 answers

Well for example so:

var menuItem = (MenuItem)sender;
var contextMenu = (ContextMenu)menuItem.Parent;
var target = (TextBlock)contextMenu.PlacementTarget;
MessageBox.Show(target.Text);

But it is more correct to define the copy command, and define its handler.

<TextBlock Text="123">
    <TextBlock.CommandBindings>
        <CommandBinding Command="Copy" CanExecute="OnCanCopy" Executed="OnCopy"/>
    </TextBlock.CommandBindings>
    <TextBlock.ContextMenu>
        <ContextMenu x:Name="cm">
            <MenuItem Command="Copy"
                      CommandTarget="{Binding Path=Parent.PlacementTarget,
                                          RelativeSource={RelativeSource Self}}"/>
        </ContextMenu>
    </TextBlock.ContextMenu>
</TextBlock>

Code-behind:

void OnCanCopy(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = true;
}

void OnCopy(object sender, ExecutedRoutedEventArgs e)
{
    var tb = (TextBlock)sender;
    MessageBox.Show(tb.Text);
}

(This gives the advantage that the copy command is processed not only when the context menu is called.)

Unfortunately, the context menu is in a different visual tree, so we had to manually " tie " CommandTarget. Trick with Focus hence did not work for me, apparently because in in the test case, there were no elements that could get the focus.

 2
Author: VladD, 2018-03-30 10:37:27