Windows Phone 8.1 ListView MenuFlyout: Unable to open a new page with Frame.Navigate ()

advertisements

I want to open an Edit-page i've created when i click on the MenuFlyoutItem. Heres the code for my ListView:

<ListView Name="ModelListXAML" Grid.Row="1" Margin="0,12,0,0" CanDragItems="True" SelectionChanged="ModelListXAML_SelectionChanged" ItemClick="ModelListXAML_ItemClick">

        <ListView.ItemTemplate>
            <DataTemplate>
                <Grid Margin="0,0,0,5" Holding="ModellItem_Holding">
                    <FlyoutBase.AttachedFlyout>
                        <MenuFlyout>
                            <MenuFlyoutItem x:Name="ModellMenuEdit" Click="ModellMenuEdit_Click" Text="Bearbeiten"/>
                            <MenuFlyoutItem x:Name="ModellMenuDelete" Click="ModellMenuDelete_Click" Text="Löschen"/>
                        </MenuFlyout>
                    </FlyoutBase.AttachedFlyout>

                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition Height="auto"/>
                    </Grid.RowDefinitions>

                    <StackPanel Margin="10, 0,0,0">
                        <TextBlock Text="{Binding name}" FontFamily="Segoe WP Semibold" FontSize="30" HorizontalAlignment="Left" Grid.Row="0"/>
                        <TextBlock Text="{Binding captions}" FontFamily="Segoe WP Semibold" FontSize="20" HorizontalAlignment="Left" Grid.Row="1" Foreground="Gray"/>
                    </StackPanel>
                </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>

    </ListView>

My Problem is, that the app crashes, when the ModellMenuEdit_Click event get's fired. Visual Studio gives me this Error:

#if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
        UnhandledException += (sender, e) =>
        {
            if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
        };
#endif

And here's the Code for the ModelMenuEdit_Click event:

private void ModellMenuEdit_Click(object sender, RoutedEventArgs e)
    {
        Modell datacontext = (e.OriginalSource as FrameworkElement).DataContext as Modell;
        Frame.Navigate(typeof(ModellEdit));
    }

Any idea how to solve this? Thank's for any response in advance :)


The problem is with the way you're trying to retrieve the DataContext. Try this:

private void ModellMenuEdit_Click(object sender, RoutedEventArgs e)
{
    var menuFlyoutItem = sender as MenuFlyoutItem;
    Modell datacontext;

    if (menuFlyoutItem != null)
    {
        datacontext = menuFlyoutItem.DataContext as Modell;
    }

    Frame.Navigate(typeof(ModellEdit), /*in case you want to pass datacontext*/ datacontext);
}