Zakaria Ayoub
Zakaria Ayoub

Reputation: 23

Caliburn Micro Passing DataGrid as Parameter Problem

I am new to Caliburn Micro , trying to export DataGrid to excel by passing the DataGrid as paramter to a command

The passed argument to the method is always null so i get null exception

Here is XAML Code :

<DataGrid x:Name="grdPeople" ItemsSource="{Binding Path=People}"/>
<Button cal:Message.Attach="[Event Click] = [Action btnExportToExcel(grdPeople)]"  /> 

my ViewModel :

public class ShellViewModel : PropertyChangedBase
{
    private ObservableCollection<Person> people;

    public ObservableCollection<Person> People
    {
        get { return people; }
        set
        {
            people = value;
            NotifyOfPropertyChange(() => People);
        }
    }


    public ShellViewModel()
    {
        People = new ObservableCollection<Person>();
        people.Add(new Person { FirstName = "Zico", LastName = "Ayoub" });
        people.Add(new Person { FirstName = "Fibi", LastName = "Victor" });
        people.Add(new Person { FirstName = "Matthew", LastName = "Zakaria" });
        people.Add(new Person { FirstName = "Marco", LastName = "Zakaria" });

    }

    public void btnExportToExcel(DataGrid dg)
    {


        string fileName = @"d:\myfile.csv";

        dg.SelectAllCells(); // Error Here  (Object reference not set to an instance of an object)
        dg.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
        ApplicationCommands.Copy.Execute(null, dg);
        String resultat = (string)Clipboard.GetData(DataFormats.CommaSeparatedValue);
        String result = (string)Clipboard.GetData(DataFormats.Text);
        dg.UnselectAllCells();
        System.IO.StreamWriter file1 = new System.IO.StreamWriter(fileName);
        file1.WriteLine(result);
        file1.Close();

    }

}

i expect to have and instance of the DataGrid to be passed , but i got null DataGrid

Upvotes: 2

Views: 295

Answers (1)

mm8
mm8

Reputation: 169380

If you really do want to pass a reference to an element to the view model, you could use the long syntax:

<Button xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Click">
            <cal:ActionMessage MethodName="btnExportToExcel">
                <cal:Parameter Value="{Binding ElementName=grdPeople}" />
            </cal:ActionMessage>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

But a view model shouldn't reference a DataGrid if you follow the MVVM design pattern.

Upvotes: 1

Related Questions