问题描述:

I am from VB.Net WinForms comming. Now I wanted to write a small app in WPF, listing some files in a datagridview. I used WPF's DataGrid, created some Columns. And then failed to add my rows.

Please, can you help me to select the right way to get my filenames, state-text and thumbnails added to the DataGrid Row?

In VB.Net WinForms I can add a row like this:

Datagridview1.Rows.add(Myvalue, "RowStateText", "Hello World", MyDate)

In WPF's DataGrid I can add

DataGrid1.Items.Add(New DataGridRow())

But how to fill my DataGridRow?

 Private Sub AddFilesAndFolders(ByVal Base As IO.DirectoryInfo, ByRef dgv As DataGrid)

'For Each di As IO.DirectoryInfo In Base.GetDirectories

' Call AddFilesAndFolders(di, dgv)

'Next

Dim item As DataGridRow

For Each fi As IO.FileInfo In Base.GetFiles

item = New DataGridRow'<-- test 1 (row is added but empty)

Dim di As New MyFileInfo'<-- test 2 (my own class with public members, but how to add as row with declared columns?)

di.FileName = fi.FullName

di.FileDate = fi.LastAccessTime

item.Item = fi.FullName

dgv.Items.Add(di)

Next

End Sub

网友答案:

Hi: you should set an ItemsSource instead of adding items manually. If the columns are set up correctly then it will just 'work'!

dbv.ItemsSource = Base.GetFiles

or

dbv.ItemsSource = CreateMyFileInfos(Base.GetFiles)

If you have any more problems, please post back here.

Edit: on second inspection it looks like you may want to be doing it recursively. In which case your AddFilesAndFolders could instead be CreateFilesAndFolders, which would return a collection of FileInfo/MyFileInfo objects, merged with the collections produced by the child folders recursively; then bind the whole list returned from the first call, to the grid.

Hope that helps!

网友答案:

WPF is a mindset change, you need to get away from the Winforms way of thinking.

Ultimately you need to set the ItemsSource to an IEnumerable, preferably a ObservableCollection.

The quickest way to get started would be to put the ObservableCollection as a public property in your code-behind file:

public ObservableCollection<DirectoryInfo> files { get;set; }

Then in the constructor or a Load event on the Window, populate the collection with your data and then add to the Xaml declaration for your DataGrid:

ItemsSource = "{Binding Path=files}"

EDIT:

I tried this out using the DirectoryInfo class, in my code behind I added:

    public ObservableCollection<DirectoryInfo> Dir = new ObservableCollection<DirectoryInfo>();
    public Window1()
    {
        InitializeComponent();
        Dir.Add(new DirectoryInfo("c:\\"));
        Dir.Add(new DirectoryInfo("c:\\temp\\"));
        dataGrid1.ItemsSource = Dir;
    }

For some reason this was not working using the Databinding via Xaml, but I did not try very hard to get it to work.

相关阅读:
Top