我有一个UWP应用程序,我目前在手机和桌面上测试它。在该App中,我在数据模板中定义了一个上下文菜单:
<DataTemplate x:Key="AccountTemplate">
<StackPanel HorizontalAlignment="Stretch"
Holding="AccountList_Holding"
RightTapped="AccountList_RightTapped">
<FlyoutBase.AttachedFlyout>
<MenuFlyout>
<MenuFlyoutItem x:Uid="Edit"
Text="Edit"
Click="Edit_OnClick" />
<MenuFlyoutItem x:Uid="Delete"
Text="Delete"
Click="Delete_OnClick" />
</MenuFlyout>
</FlyoutBase.AttachedFlyout>
<StackPanel Margin="0,0,0, 12" >
<Grid HorizontalAlignment="Stretch">
<TextBlock Text="{Binding Name}"
TextTrimming="CharacterEllipsis"
Style="{ThemeResource SubtitleTextBlockStyle}"/>
<TextBlock TextAlignment="Right"
Style="{ThemeResource SubtitleTextBlockStyle}"
Text="{Binding CurrentBalance, Converter={StaticResource AmountFormatConverter}}"
HorizontalAlignment="Right" />
</Grid>
<TextBlock Text="{Binding Iban}"
Style="{StaticResource DeemphasizedBodyTextBlockStyle}" />
</StackPanel>
</StackPanel>
</DataTemplate>
在后面的代码中:
private void AccountList_Holding(object sender, HoldingRoutedEventArgs e)
{
var senderElement = sender as FrameworkElement;
var flyoutBase = FlyoutBase.GetAttachedFlyout(senderElement);
flyoutBase.ShowAt(senderElement);
}
private void AccountList_RightTapped(object sender, RightTappedRoutedEventArgs e)
{
var senderElement = sender as FrameworkElement;
var flyoutBase = FlyoutBase.GetAttachedFlyout(senderElement);
flyoutBase.ShowAt(senderElement);
}
现在我注意到,特别是在右键单击时,上下文菜单不会始终打开。经过一些尝试,我发现我必须单击其中一个TextBlock才能使它工作(当然,其中必须有一些文本)。此外,如果直接单击TextBlock,他似乎只获取数据上下文。
当我点击列表项目的任何地方时,如何实现它将触发并获取datacontext?
答案 0 :(得分:1)
您需要向ItemContainerStyle
或ListView
添加GridView
。
<GridView.ItemContainerStyle>
<Style TargetType="GridViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</GridView.ItemContainerStyle>
并将StackPanel
的{{1}}属性设为Background
。