将矩阵数组绑定到 WPF DataGrid
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28018974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Binding matrix arrays to WPF DataGrid
提问by Naser Asadi
I have 3 string arrays like this:
我有 3 个这样的字符串数组:
public string[] RowHeaders
{
get { return new[] {"RowHeader1", "RowHeader2", "RowHeader3", "RowHeader4"};
}
public string[] ColumnHeaders
{
get { return new[] {"ColumnHeader1", "ColumnHeader2", "ColumnHeader3"}; }
}
public string[][] Values
{
get { return new[]
{
new []{"Value11", "Value12", "Value13"},
new []{"Value21", "Value22", "Value23"},
new []{"Value31", "Value32", "Value33"},
new []{"Value41", "Value42", "Value43"},
}; }
}
Array sizes are unknown until run-time (array values in code snippet are for showing the concept). I want to create a WPF grid from them like
数组大小在运行时之前是未知的(代码片段中的数组值用于展示概念)。我想从它们创建一个 WPF 网格,例如
which binds to these 3 arrays and designed entirely in XAML(if possible). How?
它绑定到这 3 个数组并完全在 XAML 中设计(如果可能)。如何?
回答by ELH
here a solution using DataTable and MultipleBinding, in the xaml pass the three arrays to an IMultivaluesConverter:
这里使用 DataTable 和 MultipleBinding 的解决方案,在 xaml 中将三个数组传递给 IMultivaluesConverter:
<Grid>
<DataGrid>
<DataGrid.ItemsSource>
<MultiBinding Converter="{StaticResource MatrixToDataViewConverter}">
<Binding Path="ColumnHeaders"/>
<Binding Path="RowHeaders"/>
<Binding Path="Values"/>
</MultiBinding>
</DataGrid.ItemsSource>
</DataGrid>
</Grid>
then in the converter manage those arrays to create a DataView that will be bond to the Grid ItemSource :
然后在转换器中管理这些数组以创建一个将绑定到 Grid ItemSource 的 DataView :
public class MatrixToDataViewConverter:IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var myDataTable = new DataTable();
var colums = values[0] as string[];
var rows = values[1] as string[];
var vals = values[2] as string[][];
myDataTable.Columns.Add("---"); //The blanc corner column
foreach (var value in colums)
{
myDataTable.Columns.Add(value);
}
int index = 0;
foreach (string row in rows)
{
var tmp = new string[1 + vals[index].Count()];
vals[index].CopyTo(tmp, 1);
tmp[0] = row;
myDataTable.Rows.Add(tmp);
index++;
}
return myDataTable.DefaultView;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
output :

输出 :


