Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/apache-flex/4.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
Xamarin CollectionView可观测集合未使用搜索栏更新_Xamarin_Collectionview_Searchbar - Fatal编程技术网

Xamarin CollectionView可观测集合未使用搜索栏更新

Xamarin CollectionView可观测集合未使用搜索栏更新,xamarin,collectionview,searchbar,Xamarin,Collectionview,Searchbar,我的帐户集合视图未使用搜索栏更新。下面是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:vie

我的帐户集合视图未使用搜索栏更新。下面是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; }

    }
}
namespace Pricing051721.ViewModels
{
公共类MainPageViewModel:INotifyPropertyChanged
{
公共ObservableCollection帐户{get;set;}
公共激活导航{get;set;}
公共ICommand LogoutCommand{get;set;}
AdAuthenticationService authService;
公共可观测集合基本帐户列表;
公共MainPageViewModel()
{
Accounts=newobservecollection{newaccount{AllowUpdate=true,Address=“Wait”,Name=“Loading”};
authService=新的AdAuthenticationService();
Task.Run(异步()=>
{
如果(!authService.IsAuthenticated)
{
var response=authService.Authenticate();
等待更新(response.AccessToken,“”);
}
否则等待更新(authService.AccessToken,“”);
});
AccountSelected=新命令(异步(a)=>
{
如果(!a.AllowUpdate)
返回;
wait Navigation.PushAsync(新的UpdateAccountView(a));
返回;
var result=await UserDialogs.Instance.PromptAsync(新PromptConfig
{
InputType=InputType.Name,
OkText=“更改”,
Title=“输入新的分栏符”,
Text=a.ColumnBreak
});
if(result.Ok&&result.Text!=null&&result.Text.Trim().Equals(“”)
{
a、 ColumnBreak=result.Text;
isUpdating=true;
var ok=等待crm.Update(a);
var message=ok?“帐户已更新!”:“无法更新!”;
等待UserDialogs.Instance.AlertAsync(新的AlertConfig
{
Title=“消息”,
消息=消息,
OkText=“确定”
});
isUpdating=false;
}
},u=>!正在更新);
logout命令=新命令(新操作(()=>{
authService.Logout();
Environment.Exit(Environment.ExitCode);
}));
}
//搜寻
公共事件属性更改事件处理程序属性更改;
受保护的虚拟void NotifyPropertyChanged([CallerMemberName]字符串propertyName=”“)
{
PropertyChanged?.Invoke(这是新的PropertyChangedEventArgs(propertyName));
}
公共ICommand PerformSearch=>new命令((字符串查询)=>
{
账户=搜索账户(查询);
});
private bool isupdateing=false;
私人客户关系管理;
公共收款账户;
公共异步任务更新(字符串accessToken、字符串查询)
{
Crm.Setup(accessToken);
crm=crm.AuthenticatedCrmService;
var accounts=await crm.GetAccounts();
账户移除(0);
accounts.ForEach(a=>accounts.Add(a));
}
公共ObservableCollection SearchAccounts(字符串查询)
{
Task.Run(异步()=>
{
如果(!authService.IsAuthenticated)
{
var response=authService.Authenticate();
等待更新(response.AccessToken,“”);
}
否则等待更新(authService.AccessToken,“”);
});
baseAccountList=账户;
如果(!(查询==“”)
{
var normalizedQuery=query?.ToLower();
List accountsList=(List)Accounts.Where(f=>f.Name.ToLowerInvariant().Contains(normalizedQuery)).ToList();
ObservableCollection账户=新的ObservableCollection(账户列表);
帐户。清除();
归还账户;
}
其他的
{
账户=账户;
归还账户;
}
}
公共ICommand AccountSelected{get;set;}
}
}
我不需要一个简洁的解决方案(你可以从我的代码中看出),只需要一些可以工作的东西,谢谢

我的帐户集合视图未使用搜索栏更新

从您的代码中,您没有发布关于PerformSearch命令的代码,我不知道如何通过searchbar搜索数据。我做了一个关于通过搜索栏搜索一些数据的示例,显示在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; }
}

公共部分类第15页:内容页
{
公共页15()
{
初始化组件();
this.BindingContext=新AccountViewModel();
}
}
公共类AccountViewModel
{
公共ObservableCollection帐户列表{get;set;}
公共ObservableCollection帐户{get;set;}
公共ICommand执行搜索{get;set;}
公共帐户