0

I have a textblock and a contextmenu on it. The XAML is as below.

<TextBlock Name="tb" Margin="2,0,0,0" Text="{Binding FileName}" Grid.Column="1">
    <TextBlock.ContextMenu>
        <ContextMenu HasDropShadow="True">
            <MenuItem Tag="{Binding BlobId}" Header="Open" Click="MenuItem_OpenClick" />
            <MenuItem Tag="{Binding BlobId}" Header="Save" Click="MenuItem_SaveClick"/>
            <MenuItem Tag="{Binding BlobId}" Header="Delete" Click="MenuItem_DeleteClick" />
             <MenuItem Tag="{Binding BlobId}" Header="Audit Info" Click="MenuItem_AuditInfoClick" />
        </ContextMenu>
    </TextBlock.ContextMenu>
</TextBlock>

Now I want to get the text of a textblock on MenuItem_Click event. I will really appreciate any help or suggestions here.

Regards, Deepak

SkoolCodeian
  • 127
  • 1
  • 14
  • This will be tb.Text i suppose (in your code behind) – Alexander Smirnov Jul 22 '14 at 14:30
  • @AlexanderSmirnov, what value do you think your incorrect guess has here? Please restrict your comments to subjects that you actually know about. – Sheridan Jul 22 '14 at 14:33
  • @Sheridan, Sorry but I am not sure how my question is duplicate of the one you referred. – SkoolCodeian Jul 22 '14 at 14:48
  • @GrantWinney, yes that is what I am asking. My click events are working fine. I just want to know how can I access the TEXT property of TEXTBLOCK. – SkoolCodeian Jul 22 '14 at 14:51
  • @AlexanderSmirnov, That was my initial guess too, but I cannot see "tb" in my code-behind. Actually this textblock is a Listbox item. I can post my full XAML if required. – SkoolCodeian Jul 22 '14 at 14:52
  • @GrantWinney, unfortunately your comments are as invalid as Alexander's. The `ContextMenu` is not part of the usual visual tree, so it has no access to the `TextBox tb`. – Sheridan Jul 22 '14 at 14:58
  • @Deepak, while your question is *not* a duplicate of the linked question, the answer is the same... just read it (and the other linked questions) and you'll find your answer. – Sheridan Jul 22 '14 at 14:59
  • The first step, in the Click event handlers, try using `VisualTreeHelper` to get the root `ContextMenu` element of the clicked `MenuItem`. You can also use the `Parent` property, but that's when you know where the clicked `MenuItem` is in the visual tree of the `ContextMenu`. The next step is using the `PlacementTarget` to get access to the `TextBlock`, then you can easily get the `Text` property better using `GetValue` method. – King King Jul 22 '14 at 15:13
  • 1
    @KingKing, thanks mate your hint helped me a lot. This is how I did it in this particular scenario. `System.Windows.Controls.MenuItem mi = (System.Windows.Controls.MenuItem)sender; System.Windows.Controls.ContextMenu cm = (System.Windows.Controls.ContextMenu)mi.Parent; TextBlock tb = (TextBlock)cm.PlacementTarget; string ss = tb.Text;` – SkoolCodeian Jul 22 '14 at 15:57

0 Answers0