LostInComputer
LostInComputer

Reputation: 15410

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}}"/>

Upvotes: 3

Views: 3570

Answers (2)

cordialgerm
cordialgerm

Reputation: 8503

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();
}

Upvotes: 1

stukselbax
stukselbax

Reputation: 5935

If you use MVVM, then your ViewModel have to contain all changes of your Grid. You should create a button, for example, and Command, where Execute body will looks like this:

{
     SaveMyListToCSV(parameter);
}

Parameter should be or your DataGrid, or your source.

Upvotes: 1

Related Questions