如何从WPFlistview中删除或隐藏绑定所选项?

时间:2011-07-04 07:09:17

标签: wpf c#-4.0

我将一些值绑定到WPF listview。我想在单击或在行中选择时删除或隐藏某些行。我尝试按照以下步骤操作。

listview.Items.RemoveAt(listview.Items.IndexOf(listview.SelectedItem));

但它有异常。如何做到这一点?请帮帮我......

1 个答案:

答案 0 :(得分:0)

您可以使用MVVM模式来实现它。您将需要创建ObservableCollection,然后您可以编写命令,它将使用其集合进行初始化,并且当它应该执行时,它会通过{Binding}接收您需要删除的对象。看起来像这样:

//View model
public class FileGroupViewModel : ModelObject
{
    private ObservableCollection<FileGroup> fileGroups;
    public FileGroupViewModel ( ObservableCollection<FileGroup> _initialFileGroup )
    {
        this.fileGroups = _initialFileGroup;
    }

    public ObservableCollection<FileGroup> FileGroups
    {
        get
        {
            return fileGroups;
        }
        set
        {
            fileGroups = value;                
        }
    }

    public ICommand DeleteFileGroup
    {
        get
        {
            return new RemoveItemCommand<FileGroup>(FileGroups);
        }
    }
}

RemoveItemCommand - 是一个实现ICommand接口的模板类

public class RemoveItemCommand<T> : ICommand
{
    private ObservableCollection<T> _items;
    public RemoveItemCommand(ObservableCollection<T> items)
    {
        _items = items;
    }
    public void Execute(object parameter)
    {
        _items.Remove((T)parameter);
    }
    public bool CanExecute(object parameter)
    {
        return true;
    }
    public event EventHandler CanExecuteChanged;
}

然后,您的视图将包含类似^

的内容
<DataTemplate>
     <Button Command="{StaticResource DeleteCommand}" CommandParameter="{Binding}" Text="{Binding}" />
</DataTemplate>