XAML MVVM将SerchBar绑定到可观察的收集错误

qq24tv8q  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(130)

我试图在一个MAUI项目中的集合视图上使用搜索导航。但是,我已经把自己陷入了困境。
当我尝试搜索某些内容时,出现以下错误:
系统操作无效异常:'集合已修改;枚举操作可能无法执行'
下面是视图和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
我再也找不到故障了。

5hcedyr0

5hcedyr01#

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

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

执行此操作

Properties.Clear();

相关问题