gpt4 book ai didi

c# - 将数据绑定(bind)到 ListView

转载 作者:行者123 更新时间:2023-12-03 21:51:51 24 4
gpt4 key购买 nike

我是 DataBindings 的新手。我正在尝试将文件列表(更准确地说,一个 IEnumerable<FileInfo> )绑定(bind)到一个 ListView在 C#(Visual Studio 2010)中。这是我正在尝试做的事情(我做了很多试验,这是最简单的发布方式):

我的 XAML 是(其他地方没有定义资源/数据绑定(bind)):

        <ListView
Name="lvInvoices" Height="Auto" HorizontalAlignment="Center" VerticalAlignment="Stretch"
Width="Auto" MinWidth="150" MinHeight="100" Margin="10">
<ListView.View>
<GridView>
<GridViewColumn Header="#" Width="Auto"/>
<GridViewColumn Header="Fichero" Width="Auto" DisplayMemberBinding="{Binding Path=SourceFile}"/>
<GridViewColumn Header="Importe" Width="Auto"/>
</GridView>
</ListView.View>
</ListView>

我的“项目”类是这样的。我知道我没有触发 PropertyChanged 事件,现在我只想填充列表。

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SPInvoiceLoader
{
public class Invoice : System.ComponentModel.INotifyPropertyChanged
{
public Invoice()
{
}

public Invoice(FileInfo srcFile)
{
this.SourceFile = srcFile;
}
public FileInfo SourceFile { get; private set; }
public int SpId { get; set; }
public Decimal Amount { get; set; }
public string Nif { get; set; }
public bool Signed { get; set; }

public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
}
}

设置DataContext的代码是:

    IEnumerable<FileInfo> pdfFiles = dir.EnumerateFiles("*.pdf");
pdfFiles = pdfFiles.OrderBy(f => f.Name);
ObservableCollection<Invoice> coll = new ObservableCollection<Invoice>();
foreach (FileInfo pdfFile in pdfFiles)
{
coll.Add(new Invoice(pdfFile));
}
this.lvInvoices.DataContext = coll;

我试过设置 pdfFiles既作为局部变量又作为实例成员,但它在任何一种方式下都不起作用。

效果是根本没有更新任何项目,列表仍然是空的。

有什么建议吗?我对此很陌生,所以不要排除愚蠢的错误。

提前致谢

最佳答案

一个快速的解决方案,可以更好(使用 View 模型)...

你必须让你的 ObservableCollection 成为一个属性:

public ObservableCollection<Invoice> MyInvoices { get; set; }

在用户控件的 Loaded 事件中初始化您的集合:

this.MyInvoices = ....

在同一事件中,将您的用户控件的 DataContext 设置为其自身:

this.DataContext = this;

现在在 XAML 中做:

<ListView ItemsSource="{Binding MyInvoices}"></ListView>   

这样,当您要向用户控件添加更多内容时,只需添加属性即可准备好绑定(bind)。

关于c# - 将数据绑定(bind)到 ListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10124985/

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