由于似乎对这个问题很感兴趣并且我自己找到了解决方案,所以就到这里了(附加属性 rulez!)
为了清楚起见,我创建了模型类来包装字符串列表:
public class TableDataRow
{
public TableDataRow(List<string> cells)
{
Cells = cells;
}
public List<string> Cells { get; }
}
public class TableData
{
public TableData(List<string> columnHeaders, List<TableDataRow> rows)
{
for (int i = 0; i < rows.Count; i++)
if (rows[i].Cells.Count != columnHeaders.Count)
throw new ArgumentException(nameof(rows));
ColumnHeaders = columnHeaders;
Rows = rows;
}
public List<string> ColumnHeaders { get; }
public List<TableDataRow> Rows { get; }
}
现在我们定义附加属性:
public static class DataGridHelper
{
private static void TableDataChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var dataGrid = d as DataGrid;
var tableData = e.NewValue as TableData;
if (dataGrid != null && tableData != null)
{
dataGrid.Columns.Clear();
for (int i = 0; i < tableData.ColumnHeaders.Count; i++)
{
DataGridColumn column = new DataGridTextColumn
{
Binding = new Binding($"Cells[{i}]"),
Header = tableData.ColumnHeaders[i]
};
dataGrid.Columns.Add(column);
}
dataGrid.ItemsSource = tableData.Rows;
}
}
public static TableData GetTableData(DependencyObject obj)
{
return (TableData)obj.GetValue(TableDataProperty);
}
public static void SetTableData(DependencyObject obj, TableData value)
{
obj.SetValue(TableDataProperty, value);
}
// Using a DependencyProperty as the backing store for TableData. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TableDataProperty =
DependencyProperty.RegisterAttached("TableData",
typeof(TableData),
typeof(DataGridHelper),
new PropertyMetadata(null, TableDataChanged));
}
用法很琐碎:
(...)
xmlns:h="clr-namespace:<namespace-of-DataGridHelper>"
(...)
<DataGrid AutoGenerateColumns="False" h:DataGridHelper.TableData="{Binding ResultData}" />
显然DataContext 必须通过ResultData 发布TableData。不要忘记AutoGenerateColumns,否则您会收到额外的“单元格”列。