Search code examples
c#listviewwindows-store-appsflipview

Set SelectedIndex of ListView in FlipView_SelectionChanged event


I'm building a Photo app using a FlipView. In the BottomAppBar, I placed a ListView of all the images to be able to view the image in the FlipView when I click it in the ListView and get the image displayed in the FlipView, selected in the ListView (like a Pagination).

In the listView.selectionChanged event, I made the code that shows the image in the FlipView when I select it in the ListView. Here is the code:

    private void listView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string CurrentViewState = ApplicationView.GetForCurrentView().Orientation.ToString();
            int IndicatorIndex = listView.SelectedIndex;

            GoToPage(CurrentViewState, IndicatorIndex);
        }

    private void GoToPage(string CurrentViewState, int IndicatorIndex)
        {
            if (CurrentViewState == "Portrait") 
            {
                flipView1.SelectedIndex = IndicatorIndex;
            }
            else if (CurrentViewState == "Landscape")
            {
                if (IndicatorIndex % 2 == 0)
                    flipView1.SelectedIndex = IndicatorIndex / 2;
                else
                {
                    if (IndicatorIndex == 1)
                        flipView1.SelectedIndex = 1;
                    else
                        flipView1.SelectedIndex = (IndicatorIndex + 1) / 2;
                }
            }
        } 

Now when I need to change the listView.SelectedIndex according to the flipView.SelectedIndex

listView.SelectedIndex = flipView.SelectedIndex

I am having an Exception:

An exception of type 'System.ArgumentException' occurred in eBookApp.exe but was not handled in user code. Additional information: Value does not fall within the expected range.

I need to be able to get the same image selected in the FlipView, selected and scrollAt it in the ListView...


Solution

  • I ended up making it work by adding to my FlipView:

    SelectedIndex="{Binding Path=SelectedIndex, ElementName=listView1, Mode=TwoWay}"
    

    and to my ListView:

    SelectedIndex="{Binding Path=SelectedIndex, ElementName=flipView1, Mode=TwoWay}"
    

    Their both SelectedIndex refer to each other!