【问题标题】:Xamarin CollectionView Observable Collection not updating with SearchbarXamarin CollectionView Observable Collection 未使用搜索栏更新
【发布时间】:2021-05-19 17:19:45
【问题描述】:

我的帐户 CollectionView 未使用搜索栏进行更新。 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" xmlns:viewmodels="clr-namespace:Pricing051721.ViewModels"
             x:Class="Pricing051721.MainPage" Title="KR Pricing"
             x:Name="This">

    <ContentPage.BindingContext>
        <viewmodels:MainPageViewModel/>
    </ContentPage.BindingContext>

    <StackLayout>
        <Button Text="Logout" Command="{Binding LogoutCommand}" Margin="0,5,0,5"/>
        <SearchBar x:Name="searchBar"
                   SearchCommand="{Binding PerformSearch}"
                   SearchCommandParameter="{Binding Text, Source={x:Reference searchBar}}"/>
        <CollectionView ItemsSource="{Binding Accounts}" Margin="5">
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <StackLayout Margin="5" >
                        <StackLayout.GestureRecognizers>
                            <TapGestureRecognizer   Command="{Binding BindingContext.AccountSelected, Source={x:Reference This}}" CommandParameter="{Binding .}"/>
                        </StackLayout.GestureRecognizers>
                        <StackLayout >
                            <Label FontSize="Medium" Text="{Binding Name}" ></Label>
                            <Label Text="{Binding Address}"></Label>
                        </StackLayout>
                    </StackLayout>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
    </StackLayout>
</ContentPage>

我正在尝试搜索已在视图模型中查询的帐户,因此我不必再次访问数据库。搜索有效,但帐户未更新。

namespace Pricing051721.ViewModels
{
    public class MainPageViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<Account> Accounts { get; set; }
        public INavigation Navigation { get; set; }
        public ICommand LogoutCommand { get; set; }
        AdAuthenticationService authService;
        public ObservableCollection<Account> baseAccountList;


        public MainPageViewModel()
        {
            Accounts = new ObservableCollection<Account> { new Account { AllowUpdate = true, Address = "Wait", Name = "Loading" } };

            authService = new AdAuthenticationService();

            Task.Run(async () =>
            {

                if (!authService.IsAuthenticated)
                {
                    var response = authService.Authenticate();

                    await Update(response.AccessToken, "");
                }
                else await Update(authService.AccessToken, "");

            });



            AccountSelected = new Command<Account>(async (a) =>
            {
                if (!a.AllowUpdate)
                    return;

                await Navigation.PushAsync(new UpdateAccountView(a));

                return;
                var result = await UserDialogs.Instance.PromptAsync(new PromptConfig
                {
                    InputType = InputType.Name,
                    OkText = "Change",
                    Title = "Enter New Column Break",
                    Text = a.ColumnBreak
                });

                if (result.Ok && result.Text != null && !result.Text.Trim().Equals(""))
                {
                    a.ColumnBreak = result.Text;

                    isUpdating = true;

                    var ok = await crm.Update(a);

                    var message = ok ? "Account Updated!" : "Unable to update!";

                    await UserDialogs.Instance.AlertAsync(new AlertConfig
                    {
                        Title = "Message",
                        Message = message,
                        OkText = "Ok"
                    });
                    isUpdating = false;
                }
            }, _ => !isUpdating);

            LogoutCommand = new Command(new Action(() => {
                authService.Logout();
                Environment.Exit(Environment.ExitCode);
            }));
        }

        //search
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public ICommand PerformSearch => new Command<string>((string query) =>
        {
            Accounts = SearchAccounts(query);

        });



        private bool isUpdating = false;

        private Crm crm;
        public ObservableCollection<Account> accounts;

        public async Task Update(string accessToken, string query)
        {
            Crm.Setup(accessToken);

            crm = Crm.AuthenticatedCrmService;

            var accounts = await crm.GetAccounts();
            Accounts.RemoveAt(0);
            accounts.ForEach(a => Accounts.Add(a));
          
        }


        public ObservableCollection<Account> SearchAccounts(string query)
        {
            Task.Run(async () =>
            {

                if (!authService.IsAuthenticated)
                {
                    var response = authService.Authenticate();

                    await Update(response.AccessToken, "");
                }
                else await Update(authService.AccessToken, "");

            });

            baseAccountList = Accounts;
            if (!(query == ""))
            {
                var normalizedQuery = query?.ToLower() ?? "";
                List<Account> accountsList = (List<Account>)Accounts.Where(f => f.Name.ToLowerInvariant().Contains(normalizedQuery)).ToList();
                ObservableCollection<Account> accounts = new ObservableCollection<Account>(accountsList);
                Accounts.Clear();
                return accounts;
            }
            else
            {
                accounts = Accounts;
                return accounts;
            }
        }

        public ICommand AccountSelected { get; set; }

    }
}

我不需要一个简洁的解决方案(到目前为止,您可以从我的代码中看出),只需要一些可行的解决方案提前谢谢!

【问题讨论】:

  • Accounts 不会调用 PropertyChanged,因此当您使用 PerformSearch 中的新实例更新它时,它不会更新 UI

标签: xamarin collectionview searchbar


【解决方案1】:

我的帐户 CollectionView 未使用搜索栏更新

从您的代码中,您没有发布一些有关 PerformSearch 命令的代码,我不知道您如何通过搜索栏搜索数据。我做了一个例子,通过搜索栏搜索一些数据,显示在collectionview中,你可以根据下面的代码修改你的代码。

<SearchBar
            x:Name="searchBar"
            SearchCommand="{Binding PerformSearch}"
            SearchCommandParameter="{Binding Text, Source={x:Reference searchBar}}" />
        <CollectionView Margin="5" ItemsSource="{Binding Accounts}">
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <StackLayout Margin="5">
                        <!--<StackLayout.GestureRecognizers>
                            <TapGestureRecognizer Command="{Binding BindingContext.AccountSelected, Source={x:Reference This}}" CommandParameter="{Binding .}" />
                        </StackLayout.GestureRecognizers>-->
                        <StackLayout>
                            <Label FontSize="Medium" Text="{Binding Name}" />
                            <Label Text="{Binding Address}" />
                        </StackLayout>
                    </StackLayout>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>

public partial class Page15 : ContentPage
{
    public Page15()
    {
        InitializeComponent();
        this.BindingContext = new AccountViewModel();
    }
}
public class AccountViewModel
{
    public ObservableCollection<Account> AccountList { get; set; }
    public ObservableCollection<Account> Accounts { get; set; }
    public ICommand PerformSearch { get; set; }
    public AccountViewModel()
    {
        AccountList = new ObservableCollection<Account>();
        Accounts = new ObservableCollection<Account>();
        for(int i=0;i<30;i++)
        {
            Account a = new Account();
            a.Name = "account" + i;
            a.Address = "address " + i;
            AccountList.Add(a);
            Accounts.Add(a);
        }

        PerformSearch = new Command(search => { 
            if(search!=null)
            {
                string searchtext = (string)search;
                if (!string.IsNullOrEmpty(searchtext))
                {
                    Accounts.Clear();
                    List<Account> list= AccountList.Where((account) => account.Name.ToLower().Contains(searchtext) || account.Address.ToLower().Contains(searchtext)).ToList();
                    foreach(Account a in list)
                    {
                        Accounts.Add(a);
                    }
                    
                }
                Accounts = AccountList;
            }
            else
            {
                Accounts = AccountList;
            }             
        
        });
    }
}

public class Account
{
    public string Name { get; set; }
    public string Address { get; set; }
}

【讨论】:

    猜你喜欢
    • 2022-01-27
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 2018-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多