How can I bind a button in listviewitem to a command in ViewModel in Winrt

I have a NavigateToAccountsCommand RelayCommand property in ViewModel. When I bind the same to a button on the page, wherever you are outside the ListView, the bind command works. However, as soon as I translate it into a ListView DataTemplate, it does not work.

I tried changing the binding from NavigateToAccountsCommand to DataContext.NavigateToAccountsCommand while not working.

Appreciate your help ...

<Page x:Class="FinancePRO.App.Views.AccountsView" DataContext="{Binding AccountsViewModel, Source={StaticResource MainViewModelLocator}}" mc:Ignorable="d"> <Grid> <!--**This one is working**--> <Button Command="{Binding NavigateToAccountsCommand}" > <!--**This one is not working**--> <ListView ItemsSource="{Binding AllAccounts}" > <ListView.ItemTemplate> <DataTemplate> <StackPanel HorizontalAlignment="Stretch"> <TextBlock Text="{Binding AccountName}"/> <Button Command="{Binding NavigateToAccountsCommand}"> </Button> </DataTemplate> </ListView.ItemTemplate> </ListView> 
+8
c # winrt- xaml mvvm
source share
3 answers

When you are inside the DataTemplate ListView , your data context is the current ListView ItemsSource . Since in your AllAcounts "every single element is not called" NavigateToAccountsCommand ", the binding does not work.

To fix this, you will need to reference something outside the DataTemplate ; the following should work. It changes the binding to the link to the root grid of the DataContext , which should have the NavigateToAccountsCommand property. To reference the grid, you need to add the Name attribute, and then use the ElementName binding.

  <Grid Name="Root"> <!--**This one is working**--> <Button Command="{Binding NavigateToAccountsCommand}" > <!--**This one is not working**--> <ListView ItemsSource="{Binding AllAccounts}" > <ListView.ItemTemplate> <DataTemplate> <StackPanel HorizontalAlignment="Stretch"> <TextBlock Text="{Binding AccountName}"/> <Button Command"{Binding ElementName=Root, Path=DataContext.NavigateToAccountsCommand}"> </Button> </DataTemplate> </ListView.ItemTemplate> </ListView> </Grid> 
+12
source share

you can use

 <Button x:Name="cmdTabItemCloseButton" Style="{StaticResource TabItemCloseButtonStyle}" Grid.Column="1" Margin="15,0,0,0" Command="{Binding RelativeSource= {RelativeSource FindAncestor, AncestorType={x:Type ListView}}, Path=DataContext.NavigateToAccountsCommand}" CommandParameter="{Binding}"/> 
+3
source share

I had a similar problem (Win RT), which I solved by simply using:

  <GridView x:Name="itemGridView" ItemClick="ItemView_ItemClick" IsItemClickEnabled="True"/> 

and then in the Page class:

  private void ItemView_ItemClick(object sender, ItemClickEventArgs e) { //e is the object being clicked } 
-one
source share

All Articles