在Silverlight中从xaml将参数传递给构造函数

我从启用Silverlight的WCF服务获取数据并将其绑定到DataGrid ItemSource。 但我的ViewModel的构造函数正在获取一个参数。 我正在使用MVVM。 我希望从xaml传递参数到构造函数。 我必须在这里添加什么? 这是我在xaml中设置页面的DataContext的部分。

   

这是类的构造函数:

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

另外,这是错误:

类型’StudentViewModel’不能用作对象元素,因为它不是公共的,或者没有定义公共无参数构造函数或类型转换器。

您只能使用默认的无参数构造函数在WPF实例化对象,如错误消息所示。 所以你最好的选择是让’Type’成为DependencyProperty并为它设置绑定,然后在设置时调用你的PopulateStudents()方法。

 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