gpt4 book ai didi

c# - XAML 中的 WPF ListView 绑定(bind) ItemsSource

转载 作者:可可西里 更新时间:2023-11-01 07:56:28 29 4
gpt4 key购买 nike

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

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

}

如果我像这样在后面的代码中设置我的 ListView 的 ItemsSource

lvUsers.ItemsSource = this.People;

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

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

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

它不再有效。

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

最佳答案

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

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

关于c# - XAML 中的 WPF ListView 绑定(bind) ItemsSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26353919/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com