Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF GridView with a dynamic definition

I want to use the GridView mode of a ListView to display a set of data that my program will be receiving from an external source. The data will consist of two arrays, one of column names and one of strings values to populate the control.

I don't see how to create a suitable class that I can use as the Item in a ListView. The only way I know to populate the Items is to set it to a class with properties that represent the columns, but I have no knowledge of the columns before run-time.

I could create an ItemTemplate dynamically as described in: Create WPF ItemTemplate DYNAMICALLY at runtime but it still leaves me at a loss as to how to describe the actual data.

Any help gratefully received.

like image 364
TomDestry Avatar asked Dec 10 '08 14:12

TomDestry


1 Answers

Thanks, that is very helpful.

I used it to create a dynamic version as follows. I created the column headings as you suggested:

private void AddColumns(List<String> myColumns)
{
    GridView viewLayout = new GridView();
    for (int i = 0; i < myColumns.Count; i++)
    {
        viewLayout.Columns.Add(new GridViewColumn
        {
            Header = myColumns[i],
            DisplayMemberBinding = new Binding(String.Format("[{0}]", i))
        });
    }
    myListview.View = viewLayout;
}

Set up the ListView very simply in XAML:

<ListView Name="myListview" DockPanel.Dock="Left"/>

Created an wrapper class for ObservableCollection to hold my data:

public class MyCollection : ObservableCollection<List<String>>
{
    public MyCollection()
        : base()
    {
    }
}

And bound my ListView to it:

results = new MyCollection();

Binding binding = new Binding();
binding.Source = results;
myListview.SetBinding(ListView.ItemsSourceProperty, binding);

Then to populate it, it was just a case of clearing out any old data and adding the new:

results.Clear();
List<String> details = new List<string>();
for (int ii=0; ii < externalDataCollection.Length; ii++)
{
    details.Add(externalDataCollection[ii]);
}
results.Add(details);

There are probably neater ways of doing it, but this is very useful for my application. Thanks again.

like image 86
TomDestry Avatar answered Oct 09 '22 13:10

TomDestry