将xaml页面后面的代码属性绑定到列表视图

时间:2016-04-29 21:35:31

标签: wpf xaml listview xamarin.forms

我尝试在xaml页面后面的代码中使用名为“People”的公共静态属性,并在页面后面的代码的构造函数中填充它。然后在xaml页面中,我将该公共属性绑定到Xamarin.Forms ListView小部件的ItemsSource。但是在运行它时,我没有看到列表视图项被填充。列表视图没有显示任何内容。我在这做错了什么?请帮忙。

我猜在页面类后面的代码的构造函数是在listview的项目的数据呈现之后绑定的。但我不确定

代码:

return

2 个答案:

答案 0 :(得分:3)

表达式

public static List<Person> People; // public static property

不会声明属性,而是声明字段。

您需要的是非静态公共财产:

public static List<Person> People { get; set; }

如果稍后可能更改属性的值,则应创建一个声明属性的视图模型类,并实现INotifyPropertyChanged接口:

public class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private List<Person> people;
    public List<Person> People
    {
        get { return people; }
        set
        {
            people = value;
            OnNotifyPropertyChanged(nameof(People));
        }
    }

    private void OnNotifyPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

您可以将此类的实例分配给您的Page

的DataContext
InitializeComponent();
var viewModel = new ViewModel();
viewModel.People = getPeople();
DataContext = viewModel;

并在XAML中将绑定写为

ItemsSource="{Binding People}" 

如果您以后想要设置视图模型的People属性,只需通过DataContext属性访问它,如

((ViewModel)DataContext).People = getPeople();

或者您只是将ViewModel实例存储在类成员中。

答案 1 :(得分:-1)

请尝试使用ObservableCollection

定义这样的属性

public ObservableCollection<People> Peoples { get; set; }

然后在你的构造

Peoples=new ObservableCollection<People>();

 var p1 = new Person { Id = 1, Age = 19, FirstName = "Anna", LastName = "Larson" };
            var p2 = new Person { Id = 2, Age = 23, FirstName = "Beri", LastName = "Slovik" };
            var p3 = new Person { Id = 3, Age = 65, FirstName = "Ron", LastName = "Prelosi" };
            var p4 = new Person { Id = 4, Age = 32, FirstName = "William", LastName = "Maxel" };
            var p5 = new Person { Id = 5, Age = 71, FirstName = "Fred", LastName = "Lipez" };
            var p6 = new Person { Id = 6, Age = 44, FirstName = "Dave", LastName = "Vanoviz" };




                    Peoples.Add(p1);
                    Peoples.Add(p2);
                    Peoples.Add(p3);
                    Peoples.Add(p4);
                    Peoples.Add(p5);
                    Peoples.Add(p6);