Search code examples
c#wpfxamlmvvmdatagrid

Exporting DataGrid in MVVM way


How do I export the contents of the DataGrid into a CSV file in an MVVM way? My DataGrid contains 55 columns. All columns can be reordered or hidden.

The column order and visibility is controlled by the view model

<DataGridTextColumn Header="File Size"
                    DisplayIndex="{Binding Source={StaticResource Spy}, Path=DataContext.Columns.FileSize.Index, FallbackValue=8, Mode=TwoWay}"
                    Visibility="{Binding Source={StaticResource Spy}, Path=DataContext.Columns.FileSize.IsVisible, Converter={StaticResource VisibilityConverter}}"
                    Binding="{Binding Sample.FileSize, TargetNullValue={StaticResource NullString}}"/>

Solution

  • You could modify the solution found in Scott Hanselman Blog Post about "From Linq To CSV" to only use the Columns that are not hidden and to sort the columns in the same order as in your ViewModel.

    public string ToCsv(IEnumerable items)
    {
        var csvBuilder = new StringBuilder();
        var properties = typeof(T).GetProperties().Where(prop => Columns[prop.Name].FileSize.IsVisible).OrderBy(prop => Column[prop.Name].FileSize.Index).ToArray();
        
        foreach (T item in items)
        {
            string line = string.Join(",",properties.Select(p => p.GetValue(item, null));
            csvBuilder.AppendLine(line);
        }
        return csvBuilder.ToString();
    }