我有一个WPF列表框中的项目列表。我想让用户选择其中的几个项目,然后点击删除按钮从列表中删除这些项目。通过MVVM RelayCommand从列表框中删除SelectedItems
使用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>
我的视图模型构造设置该命令的一个实例:
RemoveTagsCommand = new RelayCommand<IList>(RemoveTags, CanRemoveTags);
我目前的工具a删除标签的感觉很笨拙,并进行了强制转换和复制。有没有更好的方法来实现这一点?
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);
}
}
不幸的是,我不能使用强类型的IList。我认为这是WPF返回的SelectedItemCollection的限制,但也可能是由于我使用的RelayCommand的特殊风格。 – dthrasher 2010-05-10 20:24:28
再看一遍,我发现真正的担忧是SelectedItems列表可能会因删除而改变,这就是为什么您要创建副本。如果是这样的话,我认为这个代码就像你会得到的一样干净。除非你想让你的RelayCommand在内部支持演员(类似于'RelayListCommand'和一个隐含的'Cast ''将IList'修改为'IList ''),否则该演员是不可避免的。 –
2010-05-10 20:36:46
谢谢,丹。你是对的 - 复制和铸造感觉有点笨拙,但它完成了工作。 – dthrasher 2010-06-10 01:26:04