从视图中检索集合到viewmodel

时间:2018-06-14 14:16:31

标签: c# wpf mvvm

我是WPF和MVVM概念的新手。我有个问题。 我已经将listView - AvaliableTestsListView(在View文件中)绑定到ViewModel中的集合。我还得到了第二个ListView - ChosenTestsListView。我希望该计划如下工作:

  • 用户双击AvaliableTestsListView
  • 中的元素
  • 双击元素添加到ChosenTestsListView(可以多次添加相同的元素)
  • 不知怎的,ChosenTestsListView中的元素列表需要传递给ViewModel(我发现我需要在vieModel中执行一个命令,该命令会将元素添加到绑定到ChosenTestsListView的可观察集合中)

我已经找到了基于命令的方法,我试图使用它,但它仍然无法正常工作。有什么建议? :)

查看代码:

<GroupBox
      Grid.Row="0"
      Grid.Column="0"
      FontWeight="Bold"
      Header="{x:Static res:Strings.TestCaseTestSelectionPageView_Header_AvailableTests}"
      Padding="2">
        <ListView x:Name="AvailableTestsListView"
            Grid.Column="0" Grid.Row="0"
              Margin="20,20,20,0"
              ItemsSource="{Binding Path=AvailableTests}">
            <ListView.InputBindings>
                <MouseBinding Gesture="LeftDoubleClick" Command="{Binding AddTestCommand}" CommandParameter="{Binding .}"/>
            </ListView.InputBindings>
        </ListView>
    </GroupBox>
    <GroupBox
      Grid.Row="0"
      Grid.Column="1"
      FontWeight="Bold"
      Header="{x:Static res:Strings.TestCaseTestSelectionPageView_Header_ChosenTests}"
      Padding="2">
        <ListView x:Name="ChosenTestsListView"
            Grid.Column="1" Grid.Row="0"
              Margin="20,20,20,0"
              ItemsSource="{Binding Path=ChosenTests}">
        </ListView>
    </GroupBox>

和ViewModel:

private RelayCommand<object> addTestCommand;
private ObservableCollection<TestCommand> chosenTests;

    public ObservableCollection<TestCommand> ChosenTests
    {
        get
        {
            if(chosenTests == null)
            {
                chosenTests = new ObservableCollection<TestCommand>();
            }
            return chosenTests;
        }
    }

    public System.Windows.Input.ICommand AddTestCommand
    {
        get
        {
            if (addTestCommand == null)
                addTestCommand = new RelayCommand<object>(
                    (o) => this.AddTest(o));

            return addTestCommand;
        }
    }

    private void AddTest(object obj)
    {
        TestCommand testCmd = obj as TestCommand;
        chosenTests.Add(testCmd);
    }

0 个答案:

没有答案