简体   繁体   中英

Picker with Data Using Data Binding XAMARIN

I have model Names with 2 fields.

public class Names

    {
      public string ID { get; set; }
      public string Name { get; set; }
    }

I need to get all names from my model Names to picker in XAMARIN.

    <Picker Title="Select a name" 
            ItemsSource="{Binding AllNames}" 
            ItemDisplayBinding="{Binding Name}" />

What is the most simple way to do it?

You would want to create an ObservableCollection with the object you want to use inside your list inside your view model. Like this:

public class ViewModel
{
        ObservableCollection<Names> allNames = new ObservableCollection<GroupedReportModel>();
        public ObservableCollection<Names> AllNames
        {
            get { return allNames; }
            set { SetProperty(ref allNames, value); }
        }
}

The SetProperty is an override you will get by adding an implementation of INotifyPropertyChanged onto your viewModel.

The code I use for that looks like this:

protected bool SetProperty<T>(ref T backingStore, T value, [CallerMemberName]string propertyName = "", Action onChanged = null)
    {
        if (EqualityComparer<T>.Default.Equals(backingStore, value))
            return false;

        backingStore = value;
        onChanged?.Invoke();
        OnPropertyChanged(propertyName);
        return true;
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
        var changed = PropertyChanged;
        if (changed == null)
            return;

        changed.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM