XAML 将矩阵数组绑定到WPF DataGrid

8yoxcaq7  于 2023-08-01  发布在  其他
关注(0)|答案(1)|浏览(93)

我有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网格从他们一样


的数据
它绑定到这3个数组,并完全用XAML设计(如果可能)。怎么做?

7cwmlq89

7cwmlq891#

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

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


输出:

相关问题