XAML 退格键时搜索栏不刷新列表

4c8rllxm  于 2023-02-06  发布在  其他
关注(0)|答案(1)|浏览(123)

我的Xamarin表单应用程序中有这个搜索栏功能,当你开始输入所有信息时,它工作得很好,但当你开始删除单词时,视图不会刷新,它只是清除所有信息。
下面是搜索的代码

private void SearchBar_TextChanged(object sender, TextChangedEventArgs e)
        {
            SearchBar searchBar = (SearchBar)sender;
            noMowersFoundLabel.IsVisible = false;
            //Check if the user cleared the text bar, if so: reload list of mowers
            if (searchBar.Text.Length == 0)
            {
                _viewModel.IsBusy = true;
                return;
            }
            //Max 6 digits in a serial number
            if (searchBar.Text.Length < 6)
            {
                //compares substrings to add to the list while the user has not entered full serial number
                var sorted = new List<Mower>();
                foreach (var m in _viewModel.Items)
                {
                    if (m.MachineSerialNumber.Length > searchBar.Text.Length)
                    {
                        //var serialNum = m.MachineSerialNumber.Substring(0, Math.Min(searchBar.Text.Length, 6));
                        if (m.MachineSerialNumber.Contains(searchBar.Text))
                        {
                            sorted.Add(m);
                        }
                    }
                }

                foreach(var m in sorted)
                {
                    if (!m.MachineSerialNumber.Contains(searchBar.Text))
                    {
                        sorted.Remove(m);
                    }
                }
                sorted.Sort((p1, p2) => (p1.MachineSerialNumber.CompareTo(p2.MachineSerialNumber)));
                if(sorted.Count != 0)
                {
                    _viewModel.Items.Clear();
                    foreach(var m in sorted)
                    {
                        _viewModel.Items.Add(m);
                    }
                }
                else
                {
                    _viewModel.Items.Clear();
                    noMowersFoundLabel.IsVisible = true;
                }
            }
            else //user has entered full serial number
            {
                Mower selectedItem = null;
                foreach (var m in _viewModel.Items)
                {
                    if(m.MachineSerialNumber == searchBar.Text)
                    {
                        selectedItem = m;
                    }
                }

                if(selectedItem != null)
                {
                    //We found the item
                    _viewModel.Items.Clear();
                    _viewModel.Items.Add(selectedItem);
                }
                else{
                    //No item found
                    _viewModel.Items.Clear();
                    noMowersFoundLabel.IsVisible = true;
                }
            }

我希望视图在您开始删除单词时填充信息

bqucvtff

bqucvtff1#

我认为没有必要区分输入字符串的长度。
我创建了一个演示并实现了这个功能,可以参考下面的代码:

    • 我的视图模型. cs**
public class MyViewModel 
{

    public ObservableCollection<Item> Items { get; set; }

    public MyViewModel() { 
        Items = new ObservableCollection<Item>();

        Items.Add(new Item { Name="name1" , MachineSerialNumber="0001"});
        Items.Add(new Item { Name = "name2", MachineSerialNumber = "0102" });
        Items.Add(new Item { Name = "name3", MachineSerialNumber = "1203" });
        Items.Add(new Item { Name = "name4", MachineSerialNumber = "11204" });

    }

    public  List<Item> GetSearchResults(string queryString)
    {
        var normalizedQuery = queryString?.ToLower() ?? "";
        return Items.Where(f => f.MachineSerialNumber.ToLowerInvariant().Contains(normalizedQuery)).ToList();
    }
}
    • 项目. cs**
public class Item 
{
    public string Name { get; set; }

    public string MachineSerialNumber { get; set; } 
}
    • 测试页面1.xaml**
<?xml version="1.0" encoding="utf-8" ?> 
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="SearchBarDemos.TestPage1">
    <ContentPage.Content>
        <StackLayout>
            <SearchBar x:Name="searchBar"
                   HorizontalOptions="Fill"
                   VerticalOptions="CenterAndExpand"
                   Placeholder="Search fruits..."
                   CancelButtonColor="Orange"
                   PlaceholderColor="Orange"
                   TextTransform="Lowercase"
                   HorizontalTextAlignment="Start"
                   TextChanged="searchBar_TextChanged"/>
            <Label Text="Type in the searchbox to filter results in realtime."
               HorizontalOptions="Fill"
               VerticalOptions="CenterAndExpand" />
            <ListView x:Name="searchResults" ItemsSource="{Binding Items}"
                  HorizontalOptions="Fill"
                  VerticalOptions="CenterAndExpand" >
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <TextCell Text="{Binding Name}"
                              Detail="{Binding MachineSerialNumber}" />
                    </DataTemplate>
                </ListView.ItemTemplate>

            </ListView>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>
    • 测试页面1.xaml.cs**
public partial class TestPage1 : ContentPage 
{

    MyViewModel _viewModel;
    public TestPage1()
    {
        InitializeComponent();

        _viewModel = new MyViewModel();
        this.BindingContext = _viewModel;

    }

    private void searchBar_TextChanged(object sender, TextChangedEventArgs e)
    {
        searchResults.ItemsSource = _viewModel.GetSearchResults(e.NewTextValue);
    }
}
    • 注:**

我将函数GetSearchResults添加到MyViewModel.cs

public  List<Item> GetSearchResults(string queryString)
    {
        var normalizedQuery = queryString?.ToLower() ?? "";
        return Items.Where(f => f.MachineSerialNumber.ToLowerInvariant().Contains(normalizedQuery)).ToList();
    }

一旦输入了输入字符串,我们可以做如下:

private void searchBar_TextChanged(object sender, TextChangedEventArgs e)
    {
        searchResults.ItemsSource = _viewModel.GetSearchResults(e.NewTextValue);
    }

相关问题