mercoledì 5 giugno 2013

Scroll di una GridView sul gruppo desiderato in una Windows Store App

Di default, in una Windows Store App, il focus in una GridView viene posizionato sull'elemento 0 del gruppo 0. Ma se volessimo cambiare questo comportamento e fare in modo che venga "aperta" ad un elemento a nostro piacimento?

Per farlo bisogna gestire l'evento itemGridView_Loaded ed utilizzare le CollectionView:

Nello XAML:
<GridView
    x:Name="itemGridView"
    AutomationProperties.AutomationId="ItemGridView"
    AutomationProperties.Name="Grouped Items"
    Grid.RowSpan="2"
    Padding="116,137,40,46"
    ItemsSource="{Binding Source={StaticResource groupedItemsViewSource}}"
    ItemTemplate="{StaticResource Standard250x250ItemTemplate}"
    SelectionMode="None"
    IsSwipeEnabled="false"
    IsItemClickEnabled="True"
    ItemClick="ItemView_ItemClick"
    Loaded="itemGridView_Loaded">

Nel code-behind:
private bool firstTime = true;
        
   private void itemGridView_Loaded(object sender, RoutedEventArgs e)
   {
        ICollectionView view;
        ICollectionViewGroup myGroup;
        Data.MyDataType myItem;
 
        if (!this.firstTime) return; else firstTime = false;
        view = itemGridView.ItemsSource as ICollectionView;
        view.CurrentChanged += view_CurrentChanged;
        int groupIndex = 2; // an integer value between 0 and # of items in the groups collection
        myGroup = view.CollectionGroups[groupIndex] as ICollectionViewGroup;
        myItem = recipeGroup.GroupItems[0] as Data.MyDataType;
        view.MoveCurrentTo(myItem);
    }
     
    private void view_CurrentChanged(object sender, object e)
    {
        ICollectionView view;
        Data.MyDataType  myItem;
         
        view = itemGridView.ItemsSource as ICollectionView;
        view.CurrentChanged -= view_CurrentChanged;
        myItem = view.CurrentItem as Data.MyDataType;
        itemGridView.ScrollIntoView(view.CurrentItem, ScrollIntoViewAlignment.Leading);
    }

Nessun commento: