我正try 在毛伊岛项目的集合视图上使用搜索导航.然而,我已经把自己陷入了困境.

当我try 搜索某些内容时,出现错误:

System.InvalidOperationException:‘集合已修改; 可能无法执行枚举操作.‘

下面是view和ViewModel:

该视图:

<?xml version="1.0" encoding="utf-8" ?>
  <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="KigooPCMauiSimple.Views.PropertyPage"
          xmlns:viewModel="clr-namespace:KigooPCMauiSimple.ViewModels.AppViewModel"
         Title="Properties">

<ContentPage.BindingContext>
 <viewModel:PropertiesViewModel/>
</ContentPage.BindingContext>
<StackLayout >

<SearchBar HorizontalOptions="FillAndExpand" 
           VerticalOptions="Start"
           Placeholder="Search Property"
           BackgroundColor="{AppThemeBinding Light={StaticResource Primary},
  Dark={StaticResource Gray500}}"
           Text="{Binding SearchTerm, Mode=TwoWay}"
           SearchCommand="{Binding SearchNameCommand}"
           
   />

<ListView ItemsSource="{Binding Properties}" 
          Margin="00,10,00,00"
          SelectedItem="{Binding SelectedItem, Mode=TwoWay}"
          >
 
  
  
  <ListView.ItemTemplate >
    <DataTemplate>
      <ViewCell>
        <StackLayout Orientation="Horizontal">
          <StackLayout.GestureRecognizers>
            <TapGestureRecognizer CommandParameter="{Binding .}"
                                    Command="{Binding Source={RelativeSource AncestorType={x:Type viewModel:PropertiesViewModel}},Path=GoToDetailsCommand}"/>

          </StackLayout.GestureRecognizers>
          <Image HeightRequest="75" WidthRequest="75" 
                 Aspect="AspectFill" Source="{Binding MainImageName}"/>

          <StackLayout Orientation="Vertical" HorizontalOptions="StartAndExpand">
            <Label Text="{Binding Name}"/>
            <Label Text="{Binding Address}" FontSize="Subtitle"/>
          </StackLayout>

        </StackLayout>
      </ViewCell>
         
    </DataTemplate>
  </ListView.ItemTemplate>
</ListView>

和视图模型

using CommunityToolkit.Mvvm.ComponentModel;
using KigooPCMauiSimple.Models;
using KigooPCMauiSimple.Services;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using CommunityToolkit.Mvvm.Input;
using System.Threading.Tasks;
using KigooPCMauiSimple.KigooTask;
using KigooPCMauiSimple.Views;

namespace KigooPCMauiSimple.ViewModels.AppViewModel
{



  public partial class PropertiesViewModel : BasePageViewModel
  {
 

   public PropertiesViewModel()
   {
     this.properties = GetProperties().Result;
   }




[ObservableProperty]
ObservableCollection<Property> properties;

[ObservableProperty]
Property selectedItem;


[ObservableProperty]
public string searchTerm;


[RelayCommand]
public void SearchName()
{



  if (string.IsNullOrEmpty(searchTerm))
  {
    searchTerm = string.Empty;
    
  }
  else
  {
    var zeSource = GetProperties().Result;
    searchTerm = searchTerm.ToLowerInvariant();
    var fiteredItems = zeSource.Where(m =>
    m.Name.ToLowerInvariant().Contains(searchTerm)
    || m.Address.ToLowerInvariant().Contains(searchTerm));

    if (fiteredItems is null)
    {
      foreach (var item in Properties)
      {
        properties.Remove(item);
      }
    }
    else
    {
      foreach (var item in Properties)
      {
        properties.Remove(item);
      }

      foreach (var item in fiteredItems)
      {
        properties.Add(item);
      }

    }

  }





}



[RelayCommand]
async Task GoToDetails(Property property)
{
  if (property is null)
  {
    return;
  }
  var detail = GetData.GetPropertyDetail(property.Id).Result;
  var description = Converters.HTMLToText(detail.Property.Description);
  detail.Property.Description = description;
  await Shell.Current.GoToAsync($"{nameof(DetailsPage)}", true,
    new Dictionary<string, object>()
    {
      {"PropertyDetailViewModel",detail }
    }

    );
}



public static async Task<ObservableCollection<Property>> GetProperties()
{
  var homeviewModel = await new PropertiesService().GetUserPropertiesViewModelAsync();

  var properties = new ObservableCollection<Property>();
  foreach (var item in homeviewModel.Properties)
  {
    properties.Add(item);
  }

  return properties;
}

}
}

您可以克隆该项目并查看整个范围on Github.

我再也找不到故障了.

推荐答案

而不是这样做,这在C#中是不允许的(您不能在迭代集合时修改它)

foreach (var item in Properties)
  {
    properties.Remove(item);
  }

这么做吧

Properties.Clear();

Csharp相关问答推荐

. net依赖注入如何避免服务类中的新

如何模拟耐久任务客户端在统一测试和获取错误在调度NewsListationInstanceAsync模拟设置

使页面内容居中

有没有办法在WPF文本框中添加复制事件的处理程序?

显示文档的ECDsa签名PDF在Adobe Reader中签名后已被更改或损坏

从VS调试器而不是测试资源管理器运行的调试NUnitDotNet测试

交替的奇数

是否由DI容器自动处理由ActivatorUilties.CreateInstance()创建的服务?

当空判断结果赋给变量时,为什么会出现可能空异常警告的解引用?

如何让游戏对象在切换场景时被销毁,但在开始新游戏时重新锁定

如何将默认区域性更改为fr-FR而不是en-US?

工厂类是如何在.NET 8中注册的?

C#System.Commandline:如何向命令添加参数以便向其传递值?

如何在C# WinForm控件中使用Windows 10/11的黑暗主题?

如何对构建在Clean架构和CQRS之上的控制器进行单元测试?

从实例扩展中调用类型的扩展方法

具有双返回类型的多路委托,仅返回最后一个方法';S结果,而不是所有方法';S结果

如何防止创建的线程超过可用硬件线程数?

NET应用程序如何跟踪websocket流量?

更改选项卡页面图标 colored颜色