开发者

Binding a matrix to datagrid

I have a Datagrid called previewTable.

I have a collection of collections of strings which represents the table data:

ObservableCollection<Observ开发者_如何学CableCollection<string>> tableData

I also have a collection of strings which represent columns headers:

ObservableCollection<string> columnsHeaders

I need to create columns using the columns headers collection, I achieve this here:

        foreach (string columnName in columnsHeaders)
        {
            DataGridTextColumn column = new DataGridTextColumn();
            column.Header = columnName;
            previewTable.Columns.Add(column);
        }

Now I need to bind the table to the data. The problem is:

previewTable.ItemsSource = table

Doesn't work.

I always have 9 column headers and each collection size in the data is 9.

Help would be appreciated


Some additional classes:

public class EntityDataRow
{
    public List<string> Items { get; set; }
}

public class RowItemsConverter : IValueConverter //converter for binging
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        try
        {
            var list = (List<string>) value;
            var index = (Int32) parameter;
            return list[index];
        }
        catch(Exception)
        {
            return String.Empty;
        }

    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

And this is your code (data is a list of EntityRow)

                var headers = data[0].Items;
                data.RemoveAt(0);

                PreviewGrid.Columns.Clear();
                PreviewGrid.ItemsSource = data;
                for (var i = 0; i < headers.Count; i++)
                {
                    var column = new DataGridTextColumn { Header = headers[i] };
                    var binding = new Binding("Items");
                    var converter = new RowItemsConverter();
                    binding.Converter = converter;
                    binding.ConverterParameter = i;
                    column.Binding = binding;
                    PreviewGrid.Columns.Add(column);
                }


You can use indexers in bindings so the following ought to work:-

        int i = 0;
        foreach (string columnName in columnsHeaders)
        {
            DataGridTextColumn column = new DataGridTextColumn();
            column.Header = columnName;
            column.Binding = new Binding("[" + i.ToString(); + "]");
            previewTable.Columns.Add(column);
            i += 1;
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜