Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Search Xamarin表单:联系人搜索不返回任何值_Search_Xamarin.forms_Contacts - Fatal编程技术网

Search Xamarin表单:联系人搜索不返回任何值

Search Xamarin表单:联系人搜索不返回任何值,search,xamarin.forms,contacts,Search,Xamarin.forms,Contacts,我已经使用博客从手机中获取联系人 我的代码: XAML <StackLayout> <SearchBar x:Name="filterText" HeightRequest="40" Text="{Binding SearchText}" /> <ListView ItemsSource=&q

我已经使用博客从手机中获取联系人

我的代码:

XAML

<StackLayout>
        <SearchBar x:Name="filterText"
                    HeightRequest="40"
                    Text="{Binding SearchText}" />
        <ListView   ItemsSource="{Binding FilteredContacts}"
                    HasUnevenRows="True">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Padding="10"
                                     Orientation="Horizontal">
                            <Image  Source="{Binding Image}"
                                    VerticalOptions="Center"
                                    x:Name="image"
                                    Aspect="AspectFit"
                                    HeightRequest="60"/>
                            <StackLayout VerticalOptions="Center">
                                <Label Text="{Binding Name}"
                                   FontAttributes="Bold"/>
                                <Label Text="{Binding PhoneNumbers[0]}"/>
                                <Label Text="{Binding Emails[0]}"/>
                            </StackLayout>

                            <Switch
                                Toggled="OnToggledEvent"
                                HorizontalOptions="EndAndExpand"
                                VerticalOptions="CenterAndExpand"/>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>

视图模型

public class MainViewModel: INotifyPropertyChanged
{
    IContactsService _contactService;

    public event PropertyChangedEventHandler PropertyChanged;

    public string Title => "Contacts";

    public string SearchText { get; set; }
    public ObservableCollection<Contact> Contacts { get; set; }
    public ObservableCollection<Contact> FilteredContacts
    {
        get
        {
            return string.IsNullOrEmpty(SearchText) ? Contacts : new ObservableCollection<Contact>(Contacts?.ToList()?.Where(s => !string.IsNullOrEmpty(s.Name) && s.Name.ToLower().Contains(SearchText.ToLower())));
        }
    }
    public MainViewModel(IContactsService contactService)
    {
        _contactService = contactService;
        Contacts = new ObservableCollection<Contact>();
        Xamarin.Forms.BindingBase.EnableCollectionSynchronization(Contacts, null, ObservableCollectionCallback);
        _contactService.OnContactLoaded += OnContactLoaded;
        LoadContacts();
    }


    void ObservableCollectionCallback(IEnumerable collection, object context, Action accessMethod, bool writeAccess)
    {
        // `lock` ensures that only one thread access the collection at a time
        lock (collection)
        {
            accessMethod?.Invoke();
        }
    }

    private void OnContactLoaded(object sender, ContactEventArgs e)
    {
        Contacts.Add(e.Contact);
    }
    async Task LoadContacts()
    {
        try
        {
            await _contactService.RetrieveContactsAsync();
        }
        catch (TaskCanceledException)
        {
            Console.WriteLine("Task was cancelled");
        }
    } 
}
public ObservableCollection<Contact> FilteredContacts
    {
        get
        {
            return string.IsNullOrEmpty(SearchText) ? Contacts : new ObservableCollection<Contact>(Contacts?.ToList()?.Where(s => !string.IsNullOrEmpty(s.Name) && s.Name.ToLower().Contains(SearchText.ToLower())));
        }
    }
public类主视图模型:INotifyPropertyChanged
{
i接触服务(i u contacts service);;
公共事件属性更改事件处理程序属性更改;
公共字符串标题=>“联系人”;
公共字符串SearchText{get;set;}
公共ObservableCollection联系人{get;set;}
公共可见收集筛选器已安装的联系人
{
得到
{
返回string.IsNullOrEmpty(SearchText)?Contacts:newobserveCollection(Contacts?.ToList()?。其中(s=>!string.IsNullOrEmpty(s.Name)和&s.Name.ToLower()。包含(SearchText.ToLower());
}
}
公共主视图模型(IContactsService contactService)
{
_contactService=contactService;
Contacts=新的ObservableCollection();
Xamarin.Forms.BindingBase.EnableCollectionSynchronization(Contacts,null,observeCollectionCallback);
_contactService.OnContactLoaded+=OnContactLoaded;
LoadContacts();
}
void observeCollectionCallback(IEnumerable集合、对象上下文、操作访问方法、bool writeAccess)
{
//'lock'确保一次只有一个线程访问集合
锁(集合)
{
accessMethod?.Invoke();
}
}
私有void OnContactLoaded(对象发送方,ContactEventArgs e)
{
联系人。添加(如联系人);
}
异步任务加载联系人()
{
尝试
{
wait_contactService.RetrieveContactsAsync();
}
捕获(TaskCanceledException)
{
Console.WriteLine(“任务已取消”);
}
} 
}
联系和IContact服务

public class Contact
{
    public string Name { get; set; }
    public string Image { get; set; }
    public string[] Emails { get; set; }
    public string[] PhoneNumbers { get; set; }
}

public class ContactEventArgs : EventArgs
{
    public Contact Contact { get; }
    public ContactEventArgs(Contact contact)
    {
        Contact = contact;
    }
}
public interface IContactsService
{
    event EventHandler<ContactEventArgs> OnContactLoaded;
    bool IsLoading { get; }
    Task<IList<Contact>> RetrieveContactsAsync(CancellationToken? token = null);
}
公共类联系人
{
公共字符串名称{get;set;}
公共字符串图像{get;set;}
公共字符串[]电子邮件{get;set;}
公共字符串[]电话号码{get;set;}
}
公共类ContactEventArgs:EventArgs
{
公共联系人{get;}
公共联系人事件参数(联系人)
{
接触=接触;
}
}
公共接口IContactsService
{
事件处理程序OnContactLoaded;
bool IsLoading{get;}
任务检索ContactsAsync(CancellationToken?token=null);
}
我的问题是联系人中的搜索功能不返回任何数据。

在Viewmodel中搜索代码

public class MainViewModel: INotifyPropertyChanged
{
    IContactsService _contactService;

    public event PropertyChangedEventHandler PropertyChanged;

    public string Title => "Contacts";

    public string SearchText { get; set; }
    public ObservableCollection<Contact> Contacts { get; set; }
    public ObservableCollection<Contact> FilteredContacts
    {
        get
        {
            return string.IsNullOrEmpty(SearchText) ? Contacts : new ObservableCollection<Contact>(Contacts?.ToList()?.Where(s => !string.IsNullOrEmpty(s.Name) && s.Name.ToLower().Contains(SearchText.ToLower())));
        }
    }
    public MainViewModel(IContactsService contactService)
    {
        _contactService = contactService;
        Contacts = new ObservableCollection<Contact>();
        Xamarin.Forms.BindingBase.EnableCollectionSynchronization(Contacts, null, ObservableCollectionCallback);
        _contactService.OnContactLoaded += OnContactLoaded;
        LoadContacts();
    }


    void ObservableCollectionCallback(IEnumerable collection, object context, Action accessMethod, bool writeAccess)
    {
        // `lock` ensures that only one thread access the collection at a time
        lock (collection)
        {
            accessMethod?.Invoke();
        }
    }

    private void OnContactLoaded(object sender, ContactEventArgs e)
    {
        Contacts.Add(e.Contact);
    }
    async Task LoadContacts()
    {
        try
        {
            await _contactService.RetrieveContactsAsync();
        }
        catch (TaskCanceledException)
        {
            Console.WriteLine("Task was cancelled");
        }
    } 
}
public ObservableCollection<Contact> FilteredContacts
    {
        get
        {
            return string.IsNullOrEmpty(SearchText) ? Contacts : new ObservableCollection<Contact>(Contacts?.ToList()?.Where(s => !string.IsNullOrEmpty(s.Name) && s.Name.ToLower().Contains(SearchText.ToLower())));
        }
    }
public-observeCollection-FilteredContacts
{
得到
{
返回string.IsNullOrEmpty(SearchText)?Contacts:newobserveCollection(Contacts?.ToList()?。其中(s=>!string.IsNullOrEmpty(s.Name)和&s.Name.ToLower()。包含(SearchText.ToLower());
}
}

我上传了一个示例项目供参考。

这是因为您没有定义FilteredContacts的set方法。因此,该值永远不会更改

修改ViewModel的代码,如下所示

public class ContactsViewModel : INotifyPropertyChanged
{
    IContactsService _contactService;

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    public string Title => "Contacts";


    string search;
    public string SearchText { 
        
        get { return search; } 
        
        set {
           
             if(search!=value)
            {
                search = value;
                OnPropertyChanged("SearchText");

                if (string.IsNullOrEmpty(SearchText))
                {
                    FilteredContacts  = new ObservableCollection<Contact>(Contacts);
                   
                }

                else
                {
                    
                    FilteredContacts = new ObservableCollection<Contact>(Contacts?.ToList()?.Where(s => !string.IsNullOrEmpty(s.Name) && s.Name.ToLower().Contains(SearchText.ToLower())));
                   
                }
            }

        } 
    
    }

    public ObservableCollection<Contact> Contacts { get; set; }

    ObservableCollection<Contact> filteredContacts;
    public ObservableCollection<Contact> FilteredContacts
    {
        get { return filteredContacts; } 
        
        set {
        
            if(filteredContacts!=value)
            {
                filteredContacts = value;
                OnPropertyChanged("FilteredContacts");
            }
        }
    }
    public ContactsViewModel(IContactsService contactService)
    {
        _contactService = contactService;
        Contacts = new ObservableCollection<Contact>();
        Xamarin.Forms.BindingBase.EnableCollectionSynchronization(Contacts, null, ObservableCollectionCallback);
        _contactService.OnContactLoaded += OnContactLoaded;
        LoadContacts();

        FilteredContacts = Contacts;
    }


    void ObservableCollectionCallback(IEnumerable collection, object context, Action accessMethod, bool writeAccess)
    {
        // `lock` ensures that only one thread access the collection at a time
        lock (collection)
        {
            accessMethod?.Invoke();
        }
    }

    private void OnContactLoaded(object sender, ContactEventArgs e)
    {
        Contacts.Add(e.Contact);
    }
    async Task LoadContacts()
    {
        try
        {
            await _contactService.RetrieveContactsAsync();
        }
        catch (TaskCanceledException)
        {
            Console.WriteLine("Task was cancelled");
        }
    }
}
公共类联系人查看模型:INotifyPropertyChanged
{
i接触服务(i u contacts service);;
公共事件属性更改事件处理程序属性更改;
受保护的虚拟void OnPropertyChanged([CallerMemberName]字符串propertyName=null)
{
PropertyChanged?.Invoke(这是新的PropertyChangedEventArgs(propertyName));
}
公共字符串标题=>“联系人”;
字符串搜索;
公共字符串搜索文本{
获取{return search;}
设置{
如果(搜索!=值)
{
搜索=值;
OnPropertyChanged(“搜索文本”);
if(string.IsNullOrEmpty(SearchText))
{
FilteredContacts=新的可观察到的采集(触点);
}
其他的
{
FilteredContacts=new ObservableCollection(Contacts?.ToList()?。其中(s=>!string.IsNullOrEmpty(s.Name)和&s.Name.ToLower()包含(SearchText.ToLower());
}
}
} 
}
公共ObservableCollection联系人{get;set;}
可观察收集过滤器安装的触点;
公共可见收集筛选器已安装的联系人
{
获取{return filteredContacts;}
设置{
如果(filteredContacts!=值)
{
filteredContacts=值;
已更改的不动产(“过滤式接触”);
}
}
}
公共联系人可视模型(IContacts服务联系人服务)
{
_contactService=contactService;
Contacts=新的ObservableCollection();
Xamarin.Forms.BindingBase.EnableCollectionSynchronization(Contacts,null,observeCollectionCallback);
_contactService.OnContactLoaded+=OnContactLoaded;
LoadContacts();
FilteredContacts=触点;
}
void observeCollectionCallback(IEnumerable集合、对象上下文、操作访问方法、bool writeAccess)
{
//'lock'确保一次只有一个线程访问集合
锁(集合)
{
accessMethod?.Invoke();
}
}
私有void OnContactLoaded(对象发送方,ContactEventArgs e)
{
联系人。添加(如联系人);
}
异步任务加载联系人()
{
尝试
{
wait_contactService.RetrieveContactsAsync();
}
捕获(任务C)