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

8

我在ViewModel中有一个NavigateToAccountsCommand RelayCommand属性。当我将其绑定到页面上ListView以外的任何按钮时,命令绑定都可以正常工作。但是,一旦我将其移动到ListView的DataTemplate中,它就不起作用了。

我尝试将绑定从NavigateToAccountsCommand更改为DataContext.NavigateToAccountsCommand,但仍然无法正常工作。

感谢您的帮助...

<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>
3个回答

13
当你在ListViewDataTemplate内部时,你的数据上下文是ItemsSource的当前项。由于在AllAcounts的每个元素中都没有叫做"NavigateToAccountsCommand"的属性,因此绑定不起作用。
为了修复这个问题,你需要引用DataTemplate外部的某些内容;以下内容应该起作用。它将绑定更改为引用根Grid的DataContext,该上下文应该可以访问属性NavigateToAccountsCommand。要引用Grid,必须添加Name属性,然后使用ElementName绑定。
    <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>

感谢 loopedcode 的快速回复。那解决了我的问题。 - Drunkenelf

4
你可以使用

标签


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

感谢您的及时回复,Dhaval。这在普通的WPF应用程序中可以工作,但在WinRT应用程序中无法工作。不管怎样还是非常感谢。 - Drunkenelf

-1

我曾经遇到过类似的问题(Win RT),我通过使用以下方法解决了它:

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

然后在页面类中:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接