Forum Xamarin.Forms

Announcement:

The Xamarin Forums have officially moved to the new Microsoft Q&A experience. Microsoft Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

To create new threads and ask questions head over to Microsoft Q&A for .NET and get involved today.

Updating a picker selecteditem from a listview itemselected event

jenova1628jenova1628 Member ✭✭✭
edited February 4 in Xamarin.Forms

Hi guys,
I am seem to be having a problem where I select a item from my listview and do CustomerList.SelectedItem = SearchResults.SelectedItem; but the picker stays null. basically I have a list of customers in a picker and in my listview I have the same list but I have given a button which shows a search bar in a new stacklayout .

Here is my code

How i populate my customer picker at the load
BindingContext = new JobSheetViewModel() { CustomersList = App.CustomersDatabase.GetAllCustomers().Select(c => new CustomersViewModel() { Id = c.Id, Name = c.Name }).ToList() };

my searchbar text changed function

`private void SearchBar_TextChanged(object sender, TextChangedEventArgs e)
    {
        SearchBarController = (SearchBar)sender;
        SearchResults.ItemsSource = GetCustomers(e.NewTextValue);
    }`

function to get the listdata using my viewmodel

   ` IEnumerable<CustomersViewModel> GetCustomers(string searchText = null)
    {
        var customers = new List<CustomersViewModel>();

        foreach (CustomersViewModel i in CustomerList.ItemsSource)
        {
            customers.Add(new CustomersViewModel()
            {
                Name = i.Name,
                Id = i.Id
            });
        }

        if (string.IsNullOrEmpty(searchText))
        {
            return customers;
        }

        return customers.Where(p => p.Name.StartsWith(searchText));
    }`

function for when i press a listview item

`private void SearchResults_ItemSelected(object sender, SelectedItemChangedEventArgs e)
    {
        SearchLayout.IsVisible = false;
        FormLayout.IsVisible = true;

        CustomerList.SelectedItem = SearchResults.SelectedItem;
        SearchResults.SelectedItem = null;
        SearchBarController.Text = null;
    }`
Tagged:

Posts

  • jenova1628jenova1628 Member ✭✭✭

    If I use SelectedIndex on the main thread it populates it but because i am looping through all the picker items for the listview if I change the searchbar text then the listview selected index of 0 is not that same of the pickers index

  • jenova1628jenova1628 Member ✭✭✭

    SOLVED:

    using this line of code solved the issue
    CustomerList.SelectedItem = (BindingContext as JobSheetViewModel).CustomersList.FirstOrDefault(c => c.Name == ((CustomersViewModel)e.SelectedItem).Name);

Sign In or Register to comment.