I am migrating Xamarin code to .NET MAUI. I am using PlatformEffect
to capture the RightTapped
event for WinUI.
The equivalent is done for other platforms such as Android by using the SwipeView
Control.
Shown below are partial XAML code and complete RightTappedEffect
handler classes with a bit of code missing in the event handler at the end (i.e., the code I couldn't figure out). The Effect is registered in the MauiProgram.cs (using #if WINDOWS conditional) as: effects.Add<RightTappedEffect, RightTappedPlatformEffect>();
Everything seem to work except I couldn't determine the Grid Control that generates the RightTapped
event from the very event handler.
The RightTapped
event handler returns LayoutPanel
as sender
event object. In the case of Xamarin, LayoutRenderer
is returned by sender
object and Grid
is simply Element
property of LayoutRenderer
.
My question is: How do I get the Grid
Control from the LayoutPanel
object returned by the RightTapped
event handler in MAUI, as shown at the end?
Partial XAML Code:
<ContentPage
x:Class="MauiTest.Views.MainPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:e="clr-namespace:MauiTest.Effects"
xmlns:vm="clr-namespace:MauiTest.ViewModels"
. . .
<CollectionView.GroupHeaderTemplate>
<DataTemplate>
<Grid
Margin="0"
Padding="0"
e:RightTappedEffect.Command="{Binding RightTappedCommand, Source={RelativeSource AncestorType={x:Type vm:PageViewModel}}}">
<Grid.Effects>
<e:RightTappedEffect />
</Grid.Effects>
. . .
</ContentPage>
Platform Effect Handler Classes:
public class RightTappedEffect: RoutingEffect
{
public RightTappedEffect() { }
public static readonly BindableProperty CommandProperty = BindableProperty.CreateAttached("Command", typeof(ICommand), typeof(TapAndHoldEffect), null);
public static ICommand GetCommand(BindableObject view) => (ICommand)view.GetValue(CommandProperty);
public static void SetCommand(BindableObject view, ICommand value) => view.SetValue(CommandProperty, value);
}
public class RightTappedPlatformEffect : PlatformEffect
{
public RightTappedPlatformEffect () { }
protected override void OnAttached()
{
if (this.Container is UIElement uiElement)
{
uiElement.RightTapped += UIElement_RightTapped;
}
}
protected override void OnDetached()
{
if (this.Container is UIElement uiElement)
{
uiElement.RightTapped -= UIElement_RightTapped;
}
}
private void UIElement_RightTapped(object sender, RightTappedRoutedEventArgs e)
{
if (sender is not LayoutPanel layoutPanel) return;
// debug hits this point upon right-click!
// how to get a Grid object from the layoutPanel ?????????????
}
}