Search code examples
c#windows-phonepivotviewerpivotitem

Set Pivot Selection to another in SelectionChanged event


I want to make a pivot navigating to item[0] when it was navigated from item[2] to item[1], from item[3] to item[2], etc.

Here is code:

int lastIndex = 0;
private void PageChanged(object sender, SelectionChangedEventArgs e)
        {
            switch (MainPivot.SelectedIndex)
            {
                case 0:
                    //Do smth
                    break;
                case 1:
                    //Do smth
                    break;
                case 2:
                    //Do smth
                    break;
                case 3:
                    //Do smth
                    break;
            }
            if (MainPivot.SelectedIndex + 1 == lastIndex)
            {
                MainPivot.SelectedIndex = 0;
            }
            lastIndex = MainPivot.SelectedIndex;
        }

And XAML:

    <Pivot x:Name="MainPivot" SelectionChanged="PageChanged">
        <PivotItem Margin="0" Background="Red">

        </PivotItem>
        <PivotItem Margin="0" Background="#FF0017FF">

        </PivotItem>
        <PivotItem Margin="0" Background="Yellow">

        </PivotItem>
        <PivotItem Margin="0" Background="#FFE800FF">

        </PivotItem>
    </Pivot>

But UI doesn`t react to

MainPivot.SelectedIndex = 0;

As I see, pivot will not set page until animation is over.

Is here another way to navigate to other PivotItem before navigation completed or event fires before navigation started?


Solution

  • Give a small delay before setting index to zero.

        int lastIndex = 0;
    private async void PageChanged(object sender, SelectionChangedEventArgs e)
            {
                switch (MainPivot.SelectedIndex)
                {
                    case 0:
                        //Do smth
                        break;
                    case 1:
                        //Do smth
                        break;
                    case 2:
                        //Do smth
                        break;
                    case 3:
                        //Do smth
                        break;
                }
                if (MainPivot.SelectedIndex + 1 == lastIndex)
                {
                    await Task.Delay(50);
                    MainPivot.SelectedIndex = 0;
                }
                lastIndex = MainPivot.SelectedIndex;
            }
    

    I have given await Task.Delay(50); You can optimize this by reducing the delay time.