gpt4 book ai didi

c# - 如何从绑定(bind)到 C# MVVM 中的 ObservableCollection 的列表中删除对象

转载 作者:太空宇宙 更新时间:2023-11-03 14:45:06 24 4
gpt4 key购买 nike

我正在尝试在 C# 中使用 MVVM 模式。因此我有一个客户类:

public class Customer
{
public string CustumerNumber { get; set; }
public string CustomerName { get; set; }
}

我用数据库中的客户填充列表:

public class CustomerList
{
public static List<Customer> customerlist = new List<Customer>();

public static List<Customer> GetCustomer()
{
// Get data from database
}
}

我的 View 模型:

class ViewModel : BaseViewModel
{
public ObservableCollection<Customer> Customers { get; set; }
public string CustomerSearch { get; set; }

public ViewModel()
{
Customers = new ObservableColletion<Customers>(CustomerList.GetCustomer());
}
}

我在 WPF-ListBox 中绑定(bind)了 Customers:

<ListBox ItemsSource="{Binding Customers}"
DisplayMemberPath="CustomerName"/>

假设我在 ListBox 中有 10 个 CustomerName 对象。有一个包含字符串的 TextBox。现在我想删除列表框中不包含该字符串的所有对象。我按如下方式解决了 ViewModel 中的问题:

public void SearchCustomer()
{
foreach (Customer item in Customers)
{
if (item.Customers.ToUpper().Contains(CustomerSearch.ToUpper()) == false)
{
this.Customers = new ObservableCollection<Customer>(CustomerList.RemoveItemsFromView(item));
}
}
}

这样对吗?这对我来说感觉不对,因为每次循环删除一个项目时,我都会创建一个新的 ObservableCollection 而不是操纵现有的项目。有没有更专业的方法来解决这个任务?

对于 PropertyChangeEvent 我使用 FodyWeaver

最佳答案

如果您不想创建新的源集合,您可以从现有的集合中删除项目。只要确保您不调用 Remove foreach 中的方法环形。

这应该有效:

for (int i = Customers.Count - 1; i >= 0; i--)
{
Customer item = Customers[i];
if (item.Customers.ToUpper().Contains(CustomerSearch.ToUpper()) == false)
{
Customers.RemoveAt(i);
}
}

如果您每次要添加或删除项目时都重置集合属性,您还不如使用 List<T> .只需确保在设置属性时发出属性通知即可。

关于c# - 如何从绑定(bind)到 C# MVVM 中的 ObservableCollection 的列表中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54692277/

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