使用WPF DataGrid2D绑定2d数组

时间:2016-10-26 12:44:23

标签: c# wpf xaml data-binding datagrid

我尝试将2维数组绑定到WPF中的DataGrid。我找到了这个库DataGrid2D,但是我犯了一些错误,因为它没有显示正确的结果,而是一个空的网格。

这是我的XAML代码:

 .....
  xmlns:dataGrid2D="http://gu.se/DataGrid2D"
 ....

 <Grid>
     <DataGrid Name="matrix" dataGrid2D:ItemsSource.Array2D="{Binding Data2D}"
                              dataGrid2D:ItemsSource.ColumnHeadersSource="{Binding ColumnHeaders}"
                              dataGrid2D:ItemsSource.RowHeadersSource="{Binding RowHeaders}" />
 </Grid>

这就是.cs

private String[] _columnHeaders;
public String[] ColumnHeaders
{
    get { return _columnHeaders; }
    set { _columnHeaders = value; }
}

private String[] _rowHeaders;
public String[] RowHeaders
{
    get { return _rowHeaders; }
    set { _rowHeaders = value; }
}

private bool[,] _data2D;
public bool[,] Data2D
{
    get { return _data2D; }
    set { _data2D = value; }
}


String[] columnHeaders = { "A", "B", "C" };
String[] rowHeaders = { "1", "2", "3" };
bool[,] data2D = { { true, true, false }, { true, true, false }, { true, true, false } };


ColumnHeaders = columnHeaders;
RowHeaders = rowHeaders;
Data2D = data2D;

1 个答案:

答案 0 :(得分:0)

我能够通过将属性设置器移动到我的viewmodel构造函数中并确保将viewmodel设置为xaml中的datacontext来实现此功能。

视图模型:

public class MainWindowViewModel
{
    private String[] _columnHeaders;
    public String[] ColumnHeaders
    {
        get { return _columnHeaders; }
        set { _columnHeaders = value; }
    }

    private String[] _rowHeaders;
    public String[] RowHeaders
    {
        get { return _rowHeaders; }
        set { _rowHeaders = value; }
    }

    private bool[,] _data2D;
    public bool[,] Data2D
    {
        get { return _data2D; }
        set { _data2D = value; }
    }


    String[] columnHeaders = { "A", "B", "C" };
    String[] rowHeaders = { "1", "2", "3" };
    bool[,] data2D = { { true, true, false }, { true, true, false }, { true, true, false } };

    public MainWindowViewModel()
    {
        ColumnHeaders = columnHeaders;
        RowHeaders = rowHeaders;
        Data2D = data2D;
    }
}

的Xaml:

<Window x:Class="Application.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Application"
    xmlns:dataGrid2D="http://gu.se/DataGrid2D"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
  <Window.DataContext>
    <local:MainWindowViewModel />
  </Window.DataContext>
  <Grid>
    <DataGrid Name="matrix" 
              dataGrid2D:ItemsSource.Array2D="{Binding Data2D}"
              dataGrid2D:ItemsSource.ColumnHeadersSource="{Binding ColumnHeaders}"
              dataGrid2D:ItemsSource.RowHeadersSource="{Binding RowHeaders}" />
  </Grid>
</Window>