XAML 中的 WPF ListView Binding ItemsSource [英] WPF ListView Binding ItemsSource in XAML

查看:27
本文介绍了XAML 中的 WPF ListView Binding ItemsSource的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 XAML 页面,上面有一个 ListView,定义如下

I have a simple XAML page with a ListView on it defined like this

<ListView Margin="10" Name="lvUsers" ItemsSource="{Binding People}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Name}" />
            <GridViewColumn Header="Age" Width="50" DisplayMemberBinding="{Binding Age}" />
            <GridViewColumn Header="Mail" Width="150" DisplayMemberBinding="{Binding Mail}" />
        </GridView>
    </ListView.View>
</ListView> 

在我后面的代码中:-

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

public ListView()
{
    InitializeComponent();

    this.People = new ObservableCollection<Person>();
    this.People.Add(new Person() { Name = "John Doe", Age = 42, Mail = "john@doe-family.com" });
    this.People.Add(new Person() { Name = "Jane Doe", Age = 39, Mail = "jane@doe-family.com" });
    this.People.Add(new Person() { Name = "Sammy Doe", Age = 7, Mail = "sammy.doe@gmail.com" }); 

}   

如果我像这样在后面的代码中设置我的列表视图的 ItemsSource

If I set the ItemsSource of my listview in the code behind like this

lvUsers.ItemsSource = this.People;

它工作正常,我的网格按预期显示

it works and my grid is displayed as expected

但是,如果我删除该行并尝试在 XAML 中绑定

However if I remove that line and try and bind in the XAML

<ListView Margin="10" Name="lvUsers" ItemsSource="{Binding People}">

它不再起作用.

为什么 XAML 中的绑定不起作用?

Why doesn't the binding in the XAML work?

推荐答案

如果您还没有这样做,例如在 XAML 中,您需要为您的绑定设置 DataContext.此外,由于 People 属性未实现 INotifyPropertyChanged,您可能希望在 InitializeComponent 之前创建此列表,至少在设置 DataContext,以确保在评估绑定时列表已准备就绪.您可以稍后添加到 ObservableCollection 中,但如果您在那之后创建它而不通知 UI,它将无法工作

If you don't do it already, in XAML for example, you need to set DataContext for your binding. Also since People property does not implement INotifyPropertyChanged you might want to create this list before InitializeComponent, at very least before you set DataContext, to be sure list is ready when binding is evaluated. You can add to your ObservableCollection later but if you create it after that point without notifying UI it won't work

public ListView()
{
    this.People = new ObservableCollection<Person>();
    InitializeComponent();
    this.DataContext = this;

    this.People.Add(new Person() { Name = "John Doe", Age = 42, Mail = "john@doe-family.com" });
    this.People.Add(new Person() { Name = "Jane Doe", Age = 39, Mail = "jane@doe-family.com" });
    this.People.Add(new Person() { Name = "Sammy Doe", Age = 7, Mail = "sammy.doe@gmail.com" }); 
}

这篇关于XAML 中的 WPF ListView Binding ItemsSource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆