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

标签 c# wpf mvvm

我正在尝试在 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/

相关文章:

c# - 如何获取 expando 对象的值(value) #

c# - 使用线程池复制 100.000 个文件

c# - 停止方法并等待用户输入

wpf - 如何在选择列表框中的项目时打开新的用户控件?

c# - 如何避免在 XAML/Mvvm/C# 中双击按钮

c# - 执行处理程序的子请求时出错 - 从 Controller 调用的部分 View

c# - 如何在未指定路径的代码隐藏中创建绑定(bind)?

c# - WPF ObservableCollection 两种方式绑定(bind) XML 文件

wpf - 如何连接 ViewModel 中的撤消命令以供 Ctrl-Z 调用?

mvvm - 移动模拟器上的 Prism-Mvvm 应用程序部署错误