我有一个MenuFlyout问题。我正在尝试获取一个效果良好的上下文菜单,为用户提供“删除”和“编辑”选项。但是,如果用户点击其中一个选项,则似乎没有关于如何获取列表视图或所选项目的解决方案。也许我只是对某些事情感到困惑,但我整天搜索,即使人们有类似的问题,但没有一个解决方案对我有用。
XAML :
<Pivot x:Name="MyPivot" Title="MyTitle" ItemsSource="{Binding}">
<Pivot.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding Title}"/>
</DataTemplate>
</Pivot.HeaderTemplate>
<Pivot.ItemTemplate>
<DataTemplate>
<ScrollViewer>
<ListView x:Name="MyListView" ItemsSource="{Binding Items}">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="Margin" Value="0,0,0,10"/>
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemTemplate>
<DataTemplate>
<Grid Holding="Grid_Holding">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<FlyoutBase.AttachedFlyout>
<MenuFlyout>
<MenuFlyoutItem x:Name="EditButton"
Text="Edit"
Click="EditButton_Click"/>
<MenuFlyoutItem x:Name="DeleteButton"
Text="Delete"
Click="DeleteButton_Click"/>
</MenuFlyout>
</FlyoutBase.AttachedFlyout>
// Content (TextBlocks...)
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ScrollViewer>
</DataTemplate>
</Pivot.ItemTemplate>
</Pivot>
C#
private void Grid_Holding(object sender, HoldingRoutedEventArgs e)
{
FrameworkElement senderElement = sender as FrameworkElement;
FlyoutBase flyoutBase = FlyoutBase.GetAttachedFlyout(senderElement);
flyoutBase.ShowAt(senderElement);
}
答案 0 :(得分:8)
引发click事件后,您可以获取FrameworkElement的DataContext。
private void EditButton_Click(object sender, RoutedEventArgs e)
{
var datacontext = (e.OriginalSource as FrameworkElement).DataContext;
//this datacontext is probably some object of some type T (whatever is in your Items collections you haven't specified in your question)
}