Search code examples
uwpuwp-xamltemplate10

Gridview itemclick in pivot


I have a gridview in an pivot control and I want to call a method on the viewmodel when a griditem is clicked (with an item id). I'm on a UWP project with Template10

My xaml looks like:

<Pivot Name="FeedsPivot" ItemsSource="{Binding Feeds, Mode=OneWay}">
    <Pivot.ItemTemplate>
        <DataTemplate x:DataType="models:Feed">
            <GridView Name="ArticlesGridView" ItemsSource="{Binding Articles, Mode=OneWay}">
                <GridView.ItemTemplate>
                    <DataTemplate>
                        <userControls:FeedControl />
                    </DataTemplate>
                </GridView.ItemTemplate>
            </GridView>
        </DataTemplate>
    </Pivot.ItemTemplate>
</Pivot>

I thought I could use something like this on the gridview:

ItemClick="{Binding ClickCommand, ElementName=ViewModel}"

But I always get Object reference not set to an instance of an object on the viewmodel context.
The viewmodel is referenced in the page like :

<Page.DataContext>
    <vm:MainPageViewModel x:Name="ViewModel" />
</Page.DataContext>

I also tried to give the page a name and use that in the ElementName

Any help about best practices here? Tnx in advance


Solution

  • I thought I could use something like this on the gridview:ItemClick="{Binding ClickCommand, ElementName=ViewModel}"

    We cannot directly set the Binding object to ItemClick event. In your senario the XamlBehaviors SDK is recommended to use. We can use a CallMethodAction for the Itemclick EventTriggerBehavior like follows, pay attention to enable the IsItemClickEnable for the GridView.

    XAML code as follows:

     <GridView Name="ArticlesGridView" ItemsSource="{Binding feeds, Mode=OneWay}"  IsItemClickEnabled="True"   >
         <Interactivity:Interaction.Behaviors>
             <Core:EventTriggerBehavior EventName="ItemClick">             
                 <Core:CallMethodAction TargetObject="{Binding DataContext, ElementName=root, Mode=OneWay}" MethodName="ArticlesGridView_ItemClick" />
               </Core:EventTriggerBehavior>
           </Interactivity:Interaction.Behaviors>
         <GridView.ItemTemplate>
             <DataTemplate x:DataType="models:Vipclass">
                ...
             </DataTemplate>
         </GridView.ItemTemplate>
     </GridView>
    </StackPanel>
    

    Code behind in MainPageViewModel.cs like follows:

     public void ArticlesGridView_ItemClick(object sender, ItemClickEventArgs e)
     {
        ...
     }
    

    The ElementName bind in above code snippet is the page object. For more details about how to use and install XamlBehaviors please reference the wiki of XamlBehaviors. You can also install the SDK by Xaml.Behaviors Nuget package.