I am desinging a wpf application. I code a grid(which has 35 textblocks)-wide context menu. when I click mouse's right button I need to learn on which textblock I clicked. But click event gives centext menu as a sender. How can I reach on which textblock the user click right mouse button?
My XAML code---------------------------------------------------------------:
<Grid>
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Header="Hafta İçi" x:Name="btnWeekDay" Click="btnWeekDay_Click" />
<MenuItem Header="Cuma" x:Name="btnFriday" Click="btnFriday_Click"/>
<MenuItem Header="Cumartesi" x:Name="btnSaturday" Click="btnSaturday_Click"/>
<MenuItem Header="Pazar" x:Name="btnSunday" Click="btnSunday_Click"/>
<MenuItem Header="İdari İzin" x:Name="btnAdminLeave" Click="btnAdminLeave_Click"/>
<MenuItem Header="Bayram/Tatil" x:Name="btnHoliday" Click="btnHoliday_Click" a/>
</ContextMenu>
</Grid.ContextMenu>
My C# code-------------:
private void btnWeekDay_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(sender + e.Source.ToString());
}
I found the answer. 1. I moved contextmenu from grid to the textblocks. 2. I fired contextmenuopening event and catch the texblock on which I click rght mouse button.
Here is the xaml code.
<Page.Resources>
<Style x:Key="txtBlockStyle" TargetType="{x:Type TextBlock}">
<Setter Property="TextBlock.Background" Value="AliceBlue"/>
</Style>
<Style x:Key="borderStyle" TargetType="{x:Type Border}">
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="BorderBrush" Value="DarkGreen"/>
</Style>
<ContextMenu x:Key="txtBlockContextMenu">
<MenuItem Header="Hafta İçi" x:Name="btnWeekDay" Click="btnWeekDay_Click" />
<MenuItem Header="Cuma" x:Name="btnFriday" Click="btnFriday_Click"/>
<MenuItem Header="Cumartesi" x:Name="btnSaturday" Click="btnSaturday_Click"/>
<MenuItem Header="Pazar" x:Name="btnSunday" Click="btnSunday_Click"/>
<MenuItem Header="İdari İzin" x:Name="btnAdminLeave" Click="btnAdminLeave_Click"/>
<MenuItem Header="Bayram/Tatil" x:Name="btnHoliday" Click="btnHoliday_Click" />
</ContextMenu>
</Page.Resources>
.....
<Border Style="{StaticResource borderStyle}" Grid.Column="0" Grid.Row="1" >
<TextBlock x:Name="txtDate1" ContextMenuOpening="CustomContextMenuOpening" ContextMenu="{StaticResource ResourceKey=txtBlockContextMenu}"></TextBlock>
</Border>
Here is code behind.
TextBlock targetTextBlock;
private void CustomContextMenuOpening(object sender, ContextMenuEventArgs e)
{
targetTextBlock = (TextBlock)sender;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.