tags:

views:

36

answers:

2
<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False">
  <DataGrid.Columns>
    <DataGridTextColumn Header="First Name" Binding="{Binding FirstName}" />
  </DataGrid.Columns>
</DataGrid>

In the above snippet the DataGrid columns are hard coded in the XAML.

Is it possible to have the column definitions be defined elsewhere, ideally in the MVVM View-Model, so that the columns can be defined and redefined on the fly?

A: 

of course it is possible.

i didn't think about it for more than 5 seconds but here is how you can do this: 1. define an attached property to the data grid that when set to true, you will register to the grid loaded event, when the event fires, you will extract his context from the sender parameter, than send him to a method that will fill him with the columns.

Chen Kinnrot
A: 

Using the Microsoft DataGrid with the MVVM pattern in the following way works for me because the DataGrid automatically generates the columns based on a DataTable.

In XAML I include the DataGrid:

<WpfToolkit:DataGrid 
    ItemsSource="{Binding Path=GridData, Mode=OneWay}" > 
</WpfToolkit:DataGrid> 

In my view model I expose a DataView:

public DataView GridData 
{ 
  get 
  { 
    DataSet ds = new DataSet("MyDataSet"); 

    // everything hard-coded for this example 
    int to = 12;
    int ps = 2048;
    string sv = "10";
    string st = "Open";
    string wsid = "ZAMBONI";

    DataTable dt = new DataTable("MyDataTable");
    DataColumn propertyName = new DataColumn("Property");
    DataColumn propertyValue = new DataColumn("Value");
    dt.Columns.Add(propertyName);
    dt.Columns.Add(propertyValue);
    dt.Rows.Add("Connection timeout", to);
    dt.Rows.Add("Packet size", ps);
    dt.Rows.Add("Server version", sv);
    dt.Rows.Add("State", st);
    dt.Rows.Add("Worksation id", wsid);
    ds.Tables.Add(dt);

    return ds.Tables[0].DefaultView; 
  } 
} 
Zamboni