且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将 listviewitem 中的按钮绑定到 Winrt 中 ViewModel 中的命令

更新时间:2022-01-15 17:40:08

当您在 ListViewDataTemplate 中时,您的数据上下文是ListView 的 ItemsSource.由于您的 AllAcounts' 每个单独元素中都没有名为NavigateToAccountsCommand"的属性,因此绑定不起作用.

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.

要解决这个问题,您需要从 DataTemplate 外部引用一些内容;以下应该工作.它更改绑定以引用根网格的 DataContext,它应该具有可访问的属性 NavigateToAccountsCommand.要引用网格,您必须添加 Name 属性,然后使用 ElementName 绑定.

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>