【问题标题】:Bind CommandParameter to SelectedItem of GridView将 CommandParameter 绑定到 GridView 的 SelectedItem
【发布时间】:2015-02-12 14:38:56
【问题描述】:

我在一个 Windows 8 应用程序中工作,它在一页上显示一个 GridView。当用户选择此网格中的一个项目并单击一个按钮时,下一页将加载所选项目的详细信息。

我为此使用了 MVVM,并且有来自 Prims 的 DelegateCommand:

public DelegateCommand<Route> ShowRouteDetailsCommand { get; private set; }

这个命令在构造函数内部初始化:

this.ShowRouteDetailsCommand = new DelegateCommand<Route>(this.ShowRouteDetails);

导航由 Prisms 导航服务完成:

private void ShowRouteDetails(Route route)
{
    this.NavigationService.Navigate(PageNames.RouteDetails, route.Id);
}

路线显示在 GridView 中:

                    <GridView x:Name="RouteGrid"                                  
                              ItemsSource="{Binding Routes}"
                              SelectionMode="Single">
                        <GridView.ItemTemplate>
                            <DataTemplate> ...

该命令当前已添加到应用栏内(仅用于测试):

 <AppBarButton Command="{Binding ShowRouteDetailsCommand}"
                      CommandParameter="{Binding SelectedValue,
                                                 ElementName=RouteGrid, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                      Icon="Forward" />

我的问题是,ShowRouteDetails 的参数总是空的。如果我尝试 GridViews SelectedValue 或 SelectedItem 属性,甚至都没有关系。

我知道我可以轻松添加 SelectedRoute 属性,将 SelectedItem 绑定到它并在 ShowRouteDetails 中使用它,但这对我来说似乎很脏。

【问题讨论】:

  • ElementName=RouteGrid, Mode=TwoWay,为什么是双向的?
  • 在没有找到任何解决方案后的纯粹绝望的回忆;)
  • 我建议您进行 2 项更改 1-绑定到 selecteditem 2-确保可以从按钮访问网格的名称,将它们两个放在堆栈面板中只是为了进行测试。

标签: xaml gridview mvvm winrt-xaml


【解决方案1】:

为什么不直接在 viewModel 中创建一个 var 并将其绑定到 gridView 的 SelectedItem?这样,当你运行命令时,你只需要读取那个 var 的值。

<GridView x:Name="RouteGrid" ItemsSource="{Binding Routes}"
               SelectionMode="Single" SelectedItem="{Binding myVar}">
    <GridView.ItemTemplate>
        <DataTemplate> 

【讨论】:

  • 我想给我的命令的执行方法提供它需要的所有东西而不是更改我刚刚拥有的成员变量要干净得多,因为绑定没有按我预期的那样工作。或者换一种说法:你的解决方案是我目前正在做的,但它没有达到我的期望。
猜你喜欢
  • 2012-08-23
  • 2021-11-22
  • 2018-11-22
  • 1970-01-01
  • 2017-05-16
  • 2011-08-17
  • 2014-10-10
  • 2019-12-05
  • 2012-08-26
相关资源
最近更新 更多