如何将多个选择的列表视图绑定到视图模型? [英] How to bind multiple selection of listview to viewmodel?

查看:35
本文介绍了如何将多个选择的列表视图绑定到视图模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个列表视图和一个按钮.当我在列表视图中选择多个项目,然后单击一个按钮时,我必须能够做到这一点,然后将所选项目放入列表中.但我的问题是,如何将所选项目绑定到视图模型?我将选择模式更改为多个.但是,我是否只需要这样做:

I am implementing a listview, and a button next to it. I have to be able that when i select multiple items in a listview, and then click on a button, then the selected items are put into a list. But my question is , how do i bind the selected items towards the viewmodel? I changed my selectionmode to multiple. But then, do i just have to do:

SelectedItem={Binding path= selectedItems}

然后在我的视图模型中创建一个属性 selectedItems,它会设置我选择的这些项目吗?或者这样做的正确解决方案是什么?

and then make in my viewmodel a property selectedItems, and it will set these items i have selected? Or what is the right solution to do this?

推荐答案

您可以做的是处理隐藏代码中的 Button_Click(...).然后在该代码隐藏方法中,您可以通过迭代 listView 的选定项目来创建选定项目的列表.

What you can do is you can handle the Button_Click(...) in your code-behind. Then in that code-behind method you can create a List of selected items by iterating over the selected items of the listView.

由于允许从 View 访问 ViewModel,您现在可以在 ViewModel 上调用方法并将所选项目的列表作为参数传递.

Since it is allowed to access the ViewModel from the View you can now call a method on your ViewModel and pass the list of selected items as a parameter.

我不确定这是否也仅适用于绑定,但是使用代码隐藏也不是坏习惯.

I'm not sure if this would also work with Bindings only, however it is not bad practice to use code-behind as well.

示例代码:

public void Button_Click(object sender, EventArguments arg)
{
  List<ListViewItem> mySelectedItems = new List<ListViewItem>();

  foreach(ListViewItem item in myListView.SelectedItems)
  {
    mySelectedItems.Add(item);
  }

  ViewModel.SomeMethod(mySelectedItems);
}

编辑

这是一个极简示例,XAML:

Here is a minimalist example, XAML:

<DataTemplate
            x:Key="CarTemplate"
            DataType="{x:Type Car}">
</DataTemplate>

<ListView x:Name="myListView"
          ItemsSource="{Binding Path=Cars}"
          ItemTemplate="{StaticResource CarTemplate}">
</ListView>

代码隐藏:

public void Button_Click(object sender, EventArguments arg)
    {
      List<Car> mySelectedItems = new List<Car>();

      foreach(Car item in myListView.SelectedItems)
      {
        mySelectedItems.Add(item);
      }

      ViewModel.SomeMethod(mySelectedItems);
    }

这篇关于如何将多个选择的列表视图绑定到视图模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆