BindCommand WinRT GridView并获取所选项目

时间:2013-07-02 12:00:57

标签: gridview mvvm viewmodel winrt-xaml reactiveui

我有一个GridView,它绑定到我的viewmodel上的属性Sessions。当在GridView中选择一个新项目时,我希望它能够触发导航到新视图。 Sessions属性是SessionViewModel的列表,但是它有几个具有独立对应视图的子类。我目前在我的视图代码中有这个:

this.BindCommand(ViewModel, x => x.SessionNavigateCommand, x => x.SessionsGridView, "ItemClick");

这会激活我的viewmodel上的SessionNavigateCommand,它的类型为IReactiveCommand。我想订阅这样的命令:

SessionNavigateCommand.Subscribe(x => HostScreen.Router.Navigate.Execute(x));

但事件args包装了我需要的实际viewmodel,我不想用视图特定代码污染我的viewmodel。

1 个答案:

答案 0 :(得分:0)

我在基于导航的WPF应用程序中遇到了类似的设计问题。我的解决方案是在View上的ViewModel和Navigation命令上定义Action命令,或者在托管所有内容的NavigationWindow上定义全局导航。

在某些情况下,例如在交互导致操作和导航的地方,我使用我的View level命令调用我的ViewModel命令,然后导航以完成操作。

我不确定我是否完全对这种方法感到满意,虽然它成功地实现了我的目标但感觉不对。如果你找到一个更好的解决方案,我会非常感兴趣

导致导航的示例按钮

<Button Style="{StaticResource HyperLinkButtonStyle}"                 
  Command="{Binding GoCurrentCommand, RelativeSource={RelativeSource FindAncestor, AncestorType=View:MainWindow, AncestorLevel=1}}"
  Content="Details"/>

带动作的普通按钮

<Button
  Style="{StaticResource HyperLinkButtonStyle}" 
  Command="{Binding CompleteCommand}"
  Content="Complete"/>

这是一个带有ViewModel委托的视图级别命令示例(注意使用ReactiveUI,因此语法可能不是您习惯的那样)

public class MainWindow : NavigationWindow
{
  ...
  //This defines when the command can be run
  this._completeCommand = new ReactiveCommand(((SolutionViewModel)DataContext).CompleteCommand.CanExecuteObservable); 
  //This defines what to do when the command is run
  this._completeCommand.Subscribe( 
    _ =>
    {
      ((SolutionViewModel)DataContext).CompleteCommand.Execute(null);
      this.NavigationService.Navigate(new IntentionsListPage { DataContext = this.DataContext });
    });