Bui Quang Huy
Bui Quang Huy

Reputation: 1794

Disable swipe left/right feature of Pivot in UWP

I want to cover my pivot with ScrollViewer but it does not effect because pivot has it scrollviewer itself. So I want to know the way to disable swipe left/right to change tab of Pivot.

Note: cannot use IsHitTestVisible="True" because it will disable all interaction of Pivot include tap on header to change tab

Upvotes: 0

Views: 524

Answers (1)

AVK
AVK

Reputation: 3923

If you want to Disable Left/Right Swipe on Pivot but still want to navigate to Different Pivot Items when Header is tapped, You need to Disable HorizontalScrollMode on ScrollViewer on the Pivot when Pointer is PointerEntered or PointerMoved

To Do this first We need to Gain Access to ScrollViewer Inside Pivot. To do this, I used a Helper Method that I copied from one of the answers from SO.

public static T FindChildByName<T>(DependencyObject parent, string childName) where T : DependencyObject
{
    if (parent == null) return null;
    T foundChild = null;
    int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < childrenCount; i++)
    {
        var child = VisualTreeHelper.GetChild(parent, i);
        T childType = child as T;
        if (childType == null)
        {
            foundChild = FindChildByName<T>(child, childName);
            if (foundChild != null) break;
        }
        else if (!string.IsNullOrEmpty(childName))
        {
            var frameworkElement = child as FrameworkElement;
            if (frameworkElement != null && frameworkElement.Name == childName)
            {
                foundChild = (T)child;
                break;
            }
        }
        else
        {
            foundChild = (T)child;
            break;
        }
    }
    return foundChild;
}

Now in Pivot, Activate Event Pivot_Loaded and your Pivot_Loaded should show something like below.

private void Pivot_Loaded(object sender, RoutedEventArgs e)
{
    Pivot pivot = sender as Pivot;
    int count = VisualTreeHelper.GetChildrenCount(pivot);
    ScrollViewer scrollViewer = FindChildByName<ScrollViewer>(pivot, "ScrollViewer");
    scrollViewer.PointerEntered += (s, a) => { ((ScrollViewer)s).HorizontalScrollMode = ScrollMode.Disabled; };
    scrollViewer.PointerMoved += (s, a) => { ((ScrollViewer)s).HorizontalScrollMode = ScrollMode.Disabled; };
    scrollViewer.PointerExited += (s, a) => { ((ScrollViewer)s).HorizontalScrollMode = ScrollMode.Enabled; };
    scrollViewer.PointerReleased += (s, a) => { ((ScrollViewer)s).HorizontalScrollMode = ScrollMode.Enabled; };
    scrollViewer.PointerCaptureLost += (s, a) => { ((ScrollViewer)s).HorizontalScrollMode = ScrollMode.Enabled; };
}

The whole idea of doing this is from this blog post.

Good Luck.

Upvotes: 1

Related Questions