使用数据绑定XAMARIN的数据选择器

时间:2018-02-16 00:10:06

标签: c# xamarin xamarin.forms

我的模型Names包含2个字段。

public class Names

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

我需要从我的模型Names中获取XAMARIN中的所有名称。

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

最简单的方法是什么?

1 个答案:

答案 0 :(得分:0)

您可能希望使用要在视图模型中的列表中使用的对象创建ObservableCollection。 像这样:

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

SetProperty是一个覆盖,你可以通过在viewModel上添加一个INotifyPropertyChanged的实现来获得。

我使用的代码如下所示:

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));
    }