[英]Xamarin.Forms Picker ItemsSource stays empty in XAML
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这是我的 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
. 1)使用System.Generics.ObjectModel.ObservableCollection
而不是List
。
ObservableCollection
notifies View on CollectionChanges where as List doesnot do that. ObservableCollection
通知 View on CollectionChanges 而 List 不这样做。
(Or) (或者)
2) Add items to List at initialization of List 2) 在List初始化时向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:在 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另外,这里是文档: Setting a Picker's ItemsSource Property
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.