Search code examples
c#xamlwindows-10windows-10-mobile

Flyout causing the app to crash [Windows 10] C# XAML


I want the program to show the attached Flyout when user Holding the control (on the mobile) or when the user Right-click the control (on PC).

Here is my XAML :

<DataTemplate x:DataType="data:Cards" x:Key="card">
        <StackPanel x:Name="cardstack" Holding="cardstack_Holding" KeyDown="cardstack_KeyDown" >
            <StackPanel Background="Blue" Height="100" />
            <FlyoutBase.AttachedFlyout>
                <MenuFlyout x:Name="optionpass">
                    <MenuFlyoutItem x:Name="delete" Text="Delete" Click="delete_Click"/>
                </MenuFlyout>
            </FlyoutBase.AttachedFlyout>
        </StackPanel>
    </DataTemplate>

and this is my C# :

    private void cardstack_Holding(object sender, HoldingRoutedEventArgs e)
    {
        FlyoutBase.ShowAttachedFlyout(sender as FrameworkElement);
    }

    private void cardstack_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        if (e.Key == Windows.System.VirtualKey.RightButton)
        {
            FlyoutBase.ShowAttachedFlyout(sender as FrameworkElement);
        }
    }

When I tap and Hold the Stackpanel on the mobile simulator, the Holding event works, but when I Right-click on my PC, it crashes! It says that "There are no attached Flyout!". I do not know what is wrong.

"Have you tried RightTapped event? Is it working?"

Yes and No :(


Solution

  • I just found out the solution to solve my problem.

    Turns out you have to name the MenuFlyout like my one is x:Name = "option_menu", and the Flyoutbase.AttachedFlyout cannot be in the DataTemplate, means you have to put it anywhere else except in the DataTemplate, so that the .cs file can find the name of the MenuFlyout.

    Here is my C# :

    public void cardstack_Holding(object sender, HoldingRoutedEventArgs e)
        {
            option_menu.ShowAt(sender as FrameworkElement);
            e.Handled = true;
        }
    
    private void cardstack_PointerPressed(object sender, PointerRoutedEventArgs e)
        {
            Pointer pointr = e.Pointer;
    
            if (pointr.PointerDeviceType ==  Windows.Devices.Input.PointerDeviceType.Mouse)
            {
                Windows.UI.Input.PointerPoint pointrd = e.GetCurrentPoint(sender as UIElement);
                if (pointrd.Properties.IsRightButtonPressed)
                {
                    option_menu.ShowAt(sender as FrameworkElement);
                }
            }
            e.Handled = true;
        }
    

    Notice that before this I use ShowAttachedFlyout, now I use option_menu.ShowAt.

    KeyDown event somehow did not work with my app, so I used PointerPressed instead.

    Hope this helps. (0w0)/