WPF DataGrid绑定到List中的类的属性

时间:2014-11-03 03:27:32

标签: c# wpf binding data-binding

我正在尝试将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>();

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

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

我的问题是让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')

1 个答案:

答案 0 :(得分:1)

使用ObservableCollection<File>代替List<File>并使用public类成员File

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