开发者

Exporting DataGrid in MVVM way

开发者 https://www.devze.com 2023-03-19 08:03 出处:网络
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.

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

<DataGridTextColu开发者_如何学编程mn 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}}"/>


You could modify the solution found here http://www.hanselman.com/blog/default.aspx?date=2010-02-04 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();
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消