C# – Pass parameter to constructor from xaml in Silverlight

c++silverlight

I am getting datas from Silverlight-enabled WCF service and binding it to the DataGrid ItemSource. But the constructor of my ViewModel is getting a parameter. I am using MVVM. ANd I want to pass parameter to constructor from xaml.
What must I add here?
This is the part in xaml where i am setting DataContext of page.

<navigation:Page.DataContext>
    <vms:StudentViewModel />
</navigation:Page.DataContext>

And this is the constructor of class:

 public StudentViewModel(string type)
    {
        PopulateStudents(type);
    }

Also, here is the error:

Type 'StudentViewModel' is not usable as an object element because it
is not public or does not define a public parameterless constructor or
a type converter.

Best Solution

You can only instantiate an object in WPF using the default parameter-less constructor as the error message indicates. So your best bet is to make 'Type' a DependencyProperty and set a binding up for it, then when it is set call your PopulateStudents() method.

public class StudentViewModel : DependencyObject
{
    // Parameterless constructor
    public StudentViewModel()
    {
    }

    // StudentType Dependency Property
    public string StudentType
    {
        get { return (string)GetValue(StudentTypeProperty); }
        set { SetValue(StudentTypeProperty, value); }
    }

    public static readonly DependencyProperty StudentTypeProperty =
        DependencyProperty.Register("StudentType", typeof(string), typeof(StudentViewModel), new PropertyMetadata("DefaultType", StudentTypeChanged));

    // When type changes then populate students
    private static void StudentTypeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var studentVm = d as StudentViewModel;
        if (d == null) return;

        studentVm.PopulateStudents();
    }

    public void PopulateStudents()
    {
        // Do stuff
    }

    // Other class stuff...
}

Xaml

<navigation:Page.DataContext>
    <vms:StudentViewModel StudentType="{Binding YourBindingValueHere}" />
</navigation:Page.DataContext>