我有一個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