gpt4 book ai didi

c# - 将矩阵数组绑定(bind)到 WPF DataGrid

转载 作者:行者123 更新时间:2023-11-30 20:45:35 25 4
gpt4 key购买 nike

我有 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"},
}; }
}

数组大小在运行时之前是未知的(代码片段中的数组值用于展示概念)。我想从它们创建一个 WPF 网格,例如

Grid with array data它绑定(bind)到这 3 个数组并完全用 XAML 设计(如果可能)。怎么办?

最佳答案

这里是使用 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>

然后在转换器中管理这些数组以创建将绑定(bind)到 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();
}
}

输出: enter image description here

关于c# - 将矩阵数组绑定(bind)到 WPF DataGrid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28018974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com