如何以MVVM编程方式将列添加到wpf datagrid?

时间:2013-04-02 04:02:24

标签: wpf mvvm datagrid

我想在带有MVVM应用程序的WPF中的用户界面中创建一个数据透视表。因此列数不是静态的。

我发现我可以通过编程方式从代码隐藏文件中添加列(如下面的代码片段所示)。

myDataGrid.Columns.Add(column );

但我想要使用文件背后的代码。我想用MVVM(来自视图模型)来做这件事。任何人都可以给我一个解决方案吗?

1 个答案:

答案 0 :(得分:4)

我找到了解决方案。

答案简单

  1. 在视图模型中定义DataTable
  2. 定义列(在我的情况下,我必须在programmatically循环中定义列foreach
  3. 添加行
  4. 然后将DataTable绑定到datagrid的ItemsSource属性。 (确保AutoGeneratedColumns=True
  5. 我的View Model

    private DataTable sizeQuantityTable;
    
    public DataTable SizeQuantityTable
        {
            get
            {
                return sizeQuantityTable;
            }
            set
            {
                sizeQuantityTable = value;
                NotifyPropertyChanged("SizeQuantityTable");
            }
        }
    

    我在构造函数中已经dummy data

    public MainViewModel()
    {
            this.SizeQuantityTable = new DataTable();
    
            DataColumn sizeQuantityColumn = new DataColumn();
            sizeQuantityColumn.ColumnName = "Size Quantity";
            this.SizeQuantityTable.Columns.Add(sizeQuantityColumn);
    
            DataColumn sColumn = new DataColumn();
            sColumn.ColumnName = "S";
            this.SizeQuantityTable.Columns.Add(sColumn);
    
            DataColumn mColumn = new DataColumn();
            mColumn.ColumnName = "M";
            this.SizeQuantityTable.Columns.Add(mColumn);
    
            DataRow row1 = this.SizeQuantityTable.NewRow();
            row1[sizeQuantityColumn] = "Blue";
            row1[sColumn] = "12";
            row1[mColumn] = "15";
            this.SizeQuantityTable.Rows.Add(row1);
    
            DataRow row2 = this.SizeQuantityTable.NewRow();
            row2[sizeQuantityColumn] = "Red";
            row2[sColumn] = "18";
            row2[mColumn] = "21";
            this.SizeQuantityTable.Rows.Add(row2);
    
            DataRow row3 = this.SizeQuantityTable.NewRow();
            row3[sizeQuantityColumn] = "Green";
            row3[sColumn] = "24";
            row3[mColumn] = "27";
            this.SizeQuantityTable.Rows.Add(row3);
    
            DataRow row4 = this.SizeQuantityTable.NewRow();
            row4[sizeQuantityColumn] = "Yellow";
            row4[sColumn] = "30";
            row4[mColumn] = "33";
            this.SizeQuantityTable.Rows.Add(row4);
        }
    

    我的view

    <Window x:Class="Pivot.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:vm="clr-namespace:Pivot.ViewModels"
            Title="MainWindow" Height="350" Width="525">
        <Grid>
    
            <Grid.DataContext>
                <vm:MainViewModel />
            </Grid.DataContext>
    
            <DataGrid 
                ItemsSource="{Binding SizeQuantityTable}"
                AutoGenerateColumns="True"
                />
    
        </Grid>
    </Window>