如何将列表视图项中的按钮绑定到 Winrt 中视图模型中的命令

本文关键字:视图 Winrt 模型 命令 绑定 按钮 列表 | 更新日期: 2023-09-27 18:37:16

我在 ViewModel 中有一个 NavigateToAccountsCommand RelayCommand 属性。当我将其绑定到列表视图之外页面上任何位置的按钮时,命令绑定正在工作。但是,一旦我将其移动到列表视图的数据模板,它就无法正常工作。

我尝试将绑定从 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>

如何将列表视图项中的按钮绑定到 Winrt 中视图模型中的命令

当您在ListViewDataTemplate内时,您的数据上下文是列表视图ItemsSource的当前项。由于AllAcounts每个单独的元素中没有称为" NavigateToAccountsCommand"属性,因此绑定不起作用。

要解决这个问题,你需要从DataTemplate外部引用一些东西;下面应该有效。它更改绑定以引用根 Grid 的DataContext,该应具有可访问的属性NavigateToAccountsCommand。若要引用网格,必须添加 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>
您可以使用

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

我有一个类似的问题(Win RT),我只需使用:

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

然后在 Page 类中:

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