【问题标题】:Xamarin.Forms Picker ItemsSource stays empty in XAMLXamarin.Forms Picker ItemsSource 在 XAML 中保持为空
【发布时间】:2020-06-25 08:50:23
【问题描述】:

我的选择器是空的。我已经创建了一个测试列表来特别测试它,但它也不起作用。

这是我的 XAML

<Picker x:Name="picker1" Grid.Row="1" Grid.Column="1" ItemsSource="{Binding TestList}" ItemDisplayBinding="{Binding Name}" SelectedItem="{Binding AdditionSort}"/>

这是我的代码

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

当我调试时,我可以看到我的列表是正确的。

【问题讨论】:

  • 使用 ObservableCollection 代替 List
  • 不起作用。已经试过了。
  • 您是否尝试在列表初始化时添加项目?
  • 你能告诉我你的意思吗?在 ctor 中?
  • 不在构造函数中,而是在 testList 初始化期间。 void LoadList()上方的线

标签: c# xaml mvvm xamarin.forms


【解决方案1】:

1) 使用System.Generics.ObjectModel.ObservableCollection 而不是List

ObservableCollection 在 CollectionChanges 上通知 View,而 List 没有这样做。

(或)

2) 在 List 初始化时向 List 添加项目

List<AdditionSort> testList = new List<AdditionSort>()
{
    new AdditionSort(),
    new AdditionSort(),
    new AdditionSort(),
    new AdditionSort(),
}

【讨论】:

  • 不!哦,伙计,为什么?是不是因为我用 ctor 中的对象打开了这个页面?
  • 你在哪里设置 BindingContext?
【解决方案2】:

我写了一个demo来实现绑定,你可以查看代码:

在后面的代码中:

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

在 Xaml 中:

<StackLayout>
    <!-- Place new controls here -->
    <Picker x:Name="picker1" ItemsSource="{Binding TestList}" ItemDisplayBinding="{Binding Name}" SelectedItem="{Binding AdditionSort}"/>

</StackLayout>

我上传了我的示例项目here

另外,这里是文档:Setting a Picker's ItemsSource Property

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多