我有一个 WPF ListBox 中的项目列表。我想允许用户选择其中几个项目并单击“删除”按钮以从列表中删除这些项目。
使用 MVVM RelayCommand 模式,我创建了一个具有以下签名的命令:
public RelayCommand<IList> RemoveTagsCommand { get; private set; }
在我看来,我像这样连接我的 RemoveTagsCommand:
<DockPanel>
<Button DockPanel.Dock="Right" Command="{Binding RemoveTagsCommand}" CommandParameter="{Binding ElementName=TagList, Path=SelectedItems}">Remove tags</Button>
<ListBox x:Name="TagList" ItemsSource="{Binding Tags}" SelectionMode="Extended">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.Resources>
<DataTemplate DataType="{x:Type Model:Tag}">
...
</DataTemplate>
</ListBox.Resources>
</ListBox>
</DockPanel>
我的 ViewModel 构造函数设置了一个命令实例:
RemoveTagsCommand = new RelayCommand<IList>(RemoveTags, CanRemoveTags);
我当前的 RemoveTags 实现感觉很笨拙,带有强制转换和复制。有没有更好的方法来实现这一点?
public void RemoveTags(IList toRemove)
{
var collection = toRemove.Cast<Tag>();
List<Tag> copy = new List<Tag>(collection);
foreach (Tag tag in copy)
{
Tags.Remove(tag);
}
}