Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i bind a button in listviewitem to a Command in ViewModel in Winrt

I have a NavigateToAccountsCommand RelayCommand property in the ViewModel. When I bind the same to a button on the page anywhere outside the ListView the command binding is working. However as soon as I move this to a ListView's DataTemplate its not working.

I have tried changing the binding from NavigateToAccountsCommand to DataContext.NavigateToAccountsCommand still 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>
like image 566
Drunkenelf Avatar asked Oct 28 '13 22:10

Drunkenelf


1 Answers

When you are inside the DataTemplate of the ListView, your data context is the current item of the ListView's ItemsSource. As there is nothing called "NavigateToAccountsCommand" property within your AllAcounts' each individual element, binding isn't working.

To fix that, you will need to reference something from the outside of DataTemplate; following should work. It changes the binding to reference the root Grid's DataContext which should have the property NavigateToAccountsCommand accessible. To reference the grid, you have to add Name attribute, and then use 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>
like image 133
loopedcode Avatar answered Sep 29 '22 21:09

loopedcode