【问题标题】:WPF ListView Binding ItemsSource in XAMLXAML 中的 WPF ListView 绑定 ItemsSource
【发布时间】:2014-12-08 20:09:55
【问题描述】:

我有一个简单的 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" }); 

}   

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

lvUsers.ItemsSource = this.People;

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

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

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

它不再起作用了。

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

【问题讨论】:

    标签: c# wpf xaml data-binding binding


    【解决方案1】:

    如果您还没有这样做,例如在 XAML 中,您需要为您的绑定设置 DataContext。此外,由于People 属性未实现INotifyPropertyChanged,您可能希望在InitializeComponent 之前创建此列表,至少在设置DataContext 之前,以确保在评估绑定时列表已准备好。您可以稍后添加到您的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" }); 
    }
    

    【讨论】:

    • 我认为不需要在 InitializeComponent() 之前创建列表(并且 ObservableCollection 已经实现了 INotifyPropertyChanged)。不过,您对 DataContext 需要设置是正确的。
    • 在这种情况下它是正确的,但 OP 可能不想在代码中初始化 DataContext,而是在 XAML 中初始化,然后如果你在 InitializeComponent 之后执行它,而没有 INotifyPropertyChanged,它将不会不行。
    • 有趣。以前不知道:)
    • 无论如何我已经改写了我的答案以提供更多解释
    • 是的,谢谢。为什么我在源代码中使用 lvUsers.ItemsSource = this.People 行时不必设置 DataContext?
    【解决方案2】:

    将此行放在 xaml.cs 中现有代码的后面

    this.DataContext = People;
    

    并用

    替换您的 xaml
    ItemsSource="{Binding People}" 
    

    ItemsSource="{Binding}"
    

    【讨论】:

      猜你喜欢
      • 2011-01-14
      • 2018-03-24
      • 1970-01-01
      • 2020-05-17
      • 2015-04-07
      • 1970-01-01
      • 2012-01-08
      • 1970-01-01
      • 2011-12-27
      相关资源
      最近更新 更多