简体   繁体   中英

WPF DataGrid bind to properties of class inside List

I am trying to bind a DataGrid to a List so it automatically updates when the list does.

In my 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>

In DataStorage class:

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

and the File class:

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

I add new files to the list via:

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

The list is getting filled with these file objects and the properties are not null.

My issue is getting the DataGridView to update with it?

My error:

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')

Use ObservableCollection<File> instead of List<File> And also use public member of class File .

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

AND

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM