2010-08-25 66 views
4
<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False"> 
    <DataGrid.Columns> 
    <DataGridTextColumn Header="First Name" Binding="{Binding FirstName}" /> 
    </DataGrid.Columns> 
</DataGrid> 

在上面的代码片段中,DataGrid列在XAML中被硬编码。在WPF DataGrid中动态生成列?

是否有可能在其他地方定义列定义,理想情况下是在MVVM视图模型中定义,以便可以实时定义和重新定义列?

回答

0

当然是有可能的。

我没有想过它超过5秒,但这里是你如何做到这一点: 1.定义一个附加属性到数据网格,当设置为true时,你将注册到网格加载事件,当事件触发时,你将从发送者参数中提取他的上下文,而不是发送给他一个填充列的方法。

3

以下列方式使用Microsoft DataGrid和MVVM模式适用于我,因为DataGrid会根据DataTable自动生成列。

在XAML我包括DataGrid

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

在我看来,我的模型揭露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; 
    } 
}