2016-02-11 77 views
0

我使用WPF,我有一个DataGrid绑定到一个对象列表,每个列的每个属性:WPF DataGrid中,获取数据表从视图中

<DataGrid x:Name="Docs" Margin="29,211,25,66" IsReadOnly="False" AutoGenerateColumns="False" 
       DataContext="{Binding Source={StaticResource Rutine}}" CanUserReorderColumns="False" 
       ItemsSource="{Binding Documents,Mode=TwoWay}"> 
    <DataGrid.Columns> 
     <DataGridTextColumn Header="Document Type" Binding="{Binding DocumentType}" /> 
     <DataGridTextColumn Header="Document (Name)" Binding="{Binding DocumentName}" /></DataGrid.Columns></DataGrid> 


public IList<CSDoc> Documents 
{ 
    get 
    { 
     return _Documents; 
    } 

    set 
    { 
     _Documents = value; 
     NotifyPropertyChanged("Documents"); 
    } 
} 


public class CSDoc 
{ 
    public string DocumentType{ get; set; } 
    public string DocumentName{ get; set; } 
} 

我允许用户更改数据,以便稍后可以将其导出为xls x文件。
但我需要一个DataTable对象做到这一点。
另一个问题是,我需要Headers,因为xlsx文件稍后会上传到另一个使用空格和括号进行验证的系统。
有没有一种方法来创建从DataGrid用户视图DataTable中没有循环每个单元?
而且由于每个头的,没有对象列表被循环以及...

回答

0

让您CSDoc实施INotifyPropertyChanged(实现双向绑定),并在您的视图模型层处理它。

要将IList<CSDoc>转换成一个DataTable,你可以做手工,如果只有两列(快),或使用通用的方法这里概述:Convert generic List/Enumerable to DataTable?

+0

我没有落实INPC对我的日常班,和我的列表正常工作 – Darknesstiller

+0

我只是认为它可能是某种方式采取类似的DataGrid的ViewState ... – Darknesstiller

+1

这当然是可以如此直接的做从DataGrid,但除非你正在建立一个通用的导出函数,我认为这种逻辑不应该依赖于用户界面。如果你想从UI中完成,那么是的,你需要迭代DataGrid的行和列,因为这是数据被“存储”的地方。 –

0

我觉得这个帖子盖得很好了你的问题Convert generic List/Enumerable to DataTable? 或者你可以使用迭代的方式。

try 
{ 
    var dataTable = new DataTable(); 

    dataTable.Columns.Add("DocumentType"); 
    dataTable.Columns.Add("DocumentName"); 

    foreach (CSDoc Myelement in Documents) 
    { 
     var newRow = dataTable.NewRow(); 

     // fill the properties into the cells 
     newRow["DocumentType"] = element.DocumentType; 
     newRow["DocumentName"] = element.DocumentName; 

     dataTable.Rows.Add(newRow); 
    } 

    // export to an xlsx file 
} 
catch (Exception e) 
{ 
    MessageBox.Show("error" + e.ToString()); 
}