Search code examples
c#wpfmvvminfragisticsxamdatagrid

True MVVM and third party controls


In a True MVVM model we do not expect any code behind in xaml.cs also we do not expect viewModel to have refernece of view. However all third party controls do not provide good support for True MVVM.

In my case I am using Infragistics xamDatagrid control and I want to export its data to excel. The only way I can export data to excel of data grid is by using following code:

xamDataGridExcelExporter.xamDataGridExcelExporter xamDataGridExcelExporter1 =       
   new xamDataGridExcelExporter.xamDataGridExcelExporter();   
xamDataGridExcelExporter1.Export(**this.xamDataGrid1**,   
   @"C:\Excel\ExportFile.xls");

However, XamDataGridExcelExporter takes input as this.xamDataGrid. xamDataGrid is part of View not viewModel. So how can we handle such kind of cases where we need instance of view in viewModel.


Solution

  • You can write a wrapper around xamDataGrid that has a dependencyproperty called filename. The viewmodel can then bind to this property. When the xamDataGrid detects a change on the filename property it can then execute the code you suggested. Afterwards reset the filename property for further notification.

    This solution keeps out the code from you code behind and makes the xamDataGrid responsible for exporting its data.

    -------edit---------

    A second solution can make use of the MVVM light messenger class. In stead of declaring a dependency property, make your wrapper listen to a message. When the viewmodel sends the message (which could for example have the filename as parameter) the wrapper can then execute the code.

    eg

    public class ExportableXamDataGrid: XamDataGrid
    {
        public ExportableXamDataGrid():base()
        {
            Messenger.Default.Register<string>(this,"ExportExcel",ExportFile);
        }
    
        private void ExportFile(string file)
        {
            xamDataGridExcelExporter.xamDataGridExcelExporter xamDataGridExcelExporter1 =       
            new xamDataGridExcelExporter.xamDataGridExcelExporter();   
            xamDataGridExcelExporter1.Export(**this.xamDataGrid1**,   
               @"C:\Excel\ExportFile.xls");
    
        }
    }
    

    Then in your viewmodel you can do:

     Messenger.Default.Send(@"C:\Excel\ExportFile.xls","ExportExcel");
    

    There are many solutions to your problem, all of which you do not have to start writing logic in your view.

    http://www.lucbos.net/2011/06/using-codebehind-in-mvvm.html