WPF DataGrid绑定到List中类的属性

本文关键字:属性 List DataGrid 绑定 WPF | 更新日期: 2023-09-27 18:28:47

我正在尝试将DataGrid绑定到List,以便在列表绑定时自动更新。

在我的xaml.cs:

private DataStorage dataStorage = new DataStorage();

xaml:

<DataGrid Name="DropFilesDataGrid" AutoGenerateColumns="False" ItemsSource="{Binding}">
    <DataGrid.Columns>
        <DataGridTextColumn x:Name="colFileName" Binding="{Binding fileName}" Header="File Name" />
        <DataGridTextColumn x:Name="colFileType" Binding="{Binding fileType}" Header="File Type" />
        <DataGridTextColumn x:Name="colFileLocation" Binding="{Binding fileLocation}" Header="File Location" />
    </DataGrid.Columns>
</DataGrid>

DataStorage类中:

public List<File> listOfFiles = new List<File>();

和文件类:

private string fileName { get; set; }
private long fileSize { get; set; }
private string fileImage { get; set; }
private string fileLocation { get; set; }
private string fileType { get; set; }

我通过将新文件添加到列表中

foreach (string fileDropped in files)
{
    File file = new File(fileDropped);
    dataStorage.AddFileToList(file);
}

列表中正在填充这些文件对象,并且属性不为null。

我的问题是让DataGridView更新它?

我的错误:

System.Windows.Data Error: 40 : BindingExpression path error: 'fileName' property not found on 'object' ''File' (HashCode=1820782)'. BindingExpression:Path=fileName; DataItem='File' (HashCode=1820782); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')
System.Windows.Data Error: 40 : BindingExpression path error: 'fileType' property not found on 'object' ''File' (HashCode=1820782)'. BindingExpression:Path=fileType; DataItem='File' (HashCode=1820782); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')
System.Windows.Data Error: 40 : BindingExpression path error: 'fileLocation' property not found on 'object' ''File' (HashCode=1820782)'. BindingExpression:Path=fileLocation; DataItem='File' (HashCode=1820782); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')

WPF DataGrid绑定到List中类的属性

使用ObservableCollection<File>而不是List<File>,还使用File类的public成员。

public ObservableCollection<File> listOfFiles = new ObservableCollection<File>();

  public string fileName { get; set; }
  public long fileSize { get; set; }
  public string fileImage { get; set; }
  public string fileLocation { get; set; }
  public string fileType { get; set; }
相关文章: