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

六月ゝ 毕业季﹏ 提交于 2019-12-05 03:09:11

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>

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}"/>

I had a similar problem (Win RT) which I solved by just 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
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!