【问题标题】:Implement 'Delete Item' command for multiple ListView controls为多个 ListView 控件实施“删除项目”命令
【发布时间】:2013-01-23 19:06:56
【问题描述】:

我在一个 MVVM WPF 应用程序中有多个 ListView,由 ObservableCollections 提供支持。

我正在为每个 ListView 实现一个“删除项目”上下文菜单项。目前,我将每个 ListView 的 SelectedItem 绑定到我的 ViewModel 中的同一对象。但是从 ObservableCollection 中删除项目需要 ListView 的名称(在本例中为 Wk01CECollection):

    private void DeleteLO()
    {
        this.Wk01CECollection.Remove(SelectedCE);

    }

有没有办法引用 SelectedItem 所属的 ListView?因为我需要为每个 ListView 连接一个单独的删除方法。

【问题讨论】:

    标签: wpf listview


    【解决方案1】:

    我确信这不是实现这一目标的“最佳实践”方式,但它非常简单:

    您可以将 ListView 的选定项作为参数传递给命令:

     <Button Content="Delete selected item" Command="{Binding DeleteCommand}" CommandParamenter="{Binding ElementName=SomeListView, Path=SelecteItem}" />
    

    由于您可以尝试从 ObservableCollection 中删除一个项目,即使它在集合中不存在而不会出现异常,所以在您的私有 Delete 方法中,您可以尝试从您的 ViewModel 中的所有 ObservableCollection 中删除该项目。我在这里假设一个项目不能同时在两个集合中,如果不是这种情况,我所说的将不起作用,因为您将从所有集合中删除该项目。如果您打算这样做,只需在删除之前检查 null,如果您尝试删除 null 对象,则会收到异常。

    private void DeleteLO(object listitem)
    {
        if(listitem != null)
        {
            if(listitem as CollectionType1 != null) //cast your listitem to the appropiate type inside your collection
                this.Wk01CECollection.Remove(listitem);
    
            if(listitem as CollectionType2 != null) 
                this.Wk02CECollection.Remove(listitem);
    
            //etc.
        }
    }
    

    除此之外,如果您使用 MVVM,最好 ViewModel 不知道 View,因此在 VM 中引用 ListView 会破坏该原则。

    【讨论】:

      【解决方案2】:

      我知道这个问题早已解决,但会为谷歌员工发帖。

      这对我有用:

          private void LvPrevKeyDown(object sender, KeyEventArgs e)
          {
              //Nothing to do here
              if (Lv.SelectedItems.Count == 0) return;
              //Empty space for other key combinations
      
              //Let's remove items. If it's a simple delete key so we'll remove just the selected items.
              if (e.Key != Key.Delete || Keyboard.Modifiers != ModifierKeys.None) return;
              var tmp = Lv.SelectedItems.Cast<ColorItem>().ToList();
              foreach (var colorItem in tmp)
              {
                  _cList.Remove(colorItem);
              }
          }
      

      在 xaml 中没有什么花哨的。当然,只是一些绑定到 _cList 属性的列和绑定到 _cList 的项目源。

      希望它会帮助别人! 亲切的问候!

      【讨论】:

        猜你喜欢
        • 2018-07-17
        • 1970-01-01
        • 1970-01-01
        • 2021-04-01
        • 1970-01-01
        • 2012-06-22
        • 1970-01-01
        • 1970-01-01
        • 2011-08-21
        相关资源
        最近更新 更多