我正在设计一个wpf应用程序。我编写一个网格(有35个文本块)全范围的上下文菜单。当我点击鼠标右键时,我需要了解我点击了哪个文本块。但是click事件将centext菜单作为发送者。如何到达用户单击鼠标右键的文本块?
我的XAML代码-------------------------------------------- -------------------:
<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>
我的C#代码-------------:
private void btnWeekDay_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(sender + e.Source.ToString());
}
答案 0 :(得分:0)
我找到了答案。 我将contextmenu从网格移动到了文本块。 2.我解雇了contextmenuopening事件并捕获了我点击鼠标按钮的texblock。
这是xaml代码。
<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>
这是背后的代码。
TextBlock targetTextBlock;
private void CustomContextMenuOpening(object sender, ContextMenuEventArgs e)
{
targetTextBlock = (TextBlock)sender;
}