gpt4 book ai didi

wpf - 通过 MVVM RelayCommand 从 ListBox 中删除 SelectedItems

转载 作者:行者123 更新时间:2023-12-03 10:13:13 26 4
gpt4 key购买 nike

我在 WPF 列表框中有一个项目列表。我想让用户选择其中的几个项目,然后单击“删除”按钮从列表中删除这些项目。

使用 MVVM RelayCommand 模式,我创建了一个具有以下签名的命令:

public RelayCommand<IList> RemoveTagsCommand { get; private set; }

在我的 View 中,我像这样连接我的 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);
}
}

最佳答案

我将使用 ListBox 上的 ItemContainerStyle 将项目的 IsSelected 属性绑定(bind)到模型(不是 View 模型)中的标志), 例如:

 <ListBox.ItemContainerStyle> 
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="IsSelected" Value="{Binding Path=IsSelected, Mode=TwoWay}"/>
</Style>
</ListBox.ItemContainerStyle>

那么您就不必担心传递给命令的参数是什么。此外,根据我的经验,当 View 模型中的对象很容易知道用户选择了它时,您会发现该信息的其他用途。

命令中的代码类似于:

foreach (Tag t in Tags.Where(x => x.IsSelected).ToList())
{
Tags.Remove(t);
}

关于wpf - 通过 MVVM RelayCommand 从 ListBox 中删除 SelectedItems,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2803672/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com