My picker stays empty. I already created a test list to test it in particular but it doesn't work either.
this is my XAML
<Picker x:Name="picker1" Grid.Row="1" Grid.Column="1" ItemsSource="{Binding TestList}" ItemDisplayBinding="{Binding Name}" SelectedItem="{Binding AdditionSort}"/>
this is my code behind
List<AdditionSort> TestList
{
get => testList;
set => SetValue(ref testList, value);
}
List<AdditionSort> testList = new List<AdditionSort>();
void LoadList()
{
TestList.Add(new AdditionSort { Name = "test1" });
TestList.Add(new AdditionSort { Name = "test2" });
}
when I'm debugging I can see that my list is correct.
1)Use System.Generics.ObjectModel.ObservableCollection
instead of List
.
ObservableCollection
notifies View on CollectionChanges where as List doesnot do that.
(Or)
2) Add items to List at initialization of List
List<AdditionSort> testList = new List<AdditionSort>()
{
new AdditionSort(),
new AdditionSort(),
new AdditionSort(),
new AdditionSort(),
}
I wrote a demo to make the binding work and you can check the code:
In code behind:
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
myModel m = new myModel();
BindingContext = m;
}
}
public class myModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
List<AdditionSort> testList = new List<AdditionSort>();
public List<AdditionSort> TestList
{
get { return testList; }
set
{
testList = value;
OnPropertyChanged();
}
}
public myModel() {
LoadList();
}
void LoadList()
{
TestList.Add(new AdditionSort { Name = "test1" });
TestList.Add(new AdditionSort { Name = "test2" });
}
}
public class AdditionSort
{
public string Name { get; set; }
}
And in Xaml:
<StackLayout>
<!-- Place new controls here -->
<Picker x:Name="picker1" ItemsSource="{Binding TestList}" ItemDisplayBinding="{Binding Name}" SelectedItem="{Binding AdditionSort}"/>
</StackLayout>
I uploaded my sample project here .
Also, here is the document: Setting a Picker's ItemsSource Property
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.