当前位置: 首页 > 编程语言 > C#

将参数从Silverlight中的xaml传递到构造函数Share

时间:2023-04-10 16:20:10 C#

从Silverlight中的xaml将参数传递到构造函数但是我的ViewModel的构造函数正在获取一个参数。我正在使用MVVM。我希望将参数从xaml传递给构造函数。我必须在这里添加什么?这是我在xaml中设置页面的DataContext的部分。这是该类的构造函数:publicStudentViewModel(stringtype){PopulateStudents(type);此外,错误如下:类型“StudentViewModel”不能用作对象元素,因为它不是公共的或未定义公共无参数构造函数或类型转换器。如错误消息所述,您只能使用默认的无参数构造函数在WPF中实例化对象。因此,最好的办法是将“Type”设为DependencyProperty并为其设置绑定,然后在设置时调用PopulateStudents()方法。publicclassStudentViewModel:DependencyObject{//无参数构造函数publicStudentViewModel(){}//StudentType依赖属性publicstringStudentType{get{return(string)GetValue(StudentTypeProperty);}set{SetValue(StudentTypeProperty,value);}}publicstaticreadonlyDependencyPropertyStudentTypeProperty=DependencyProperty.Register("StudentType",typeof(string),typeof(StudentViewModel),newPropertyMetadata("DefaultType",StudentTypeChanged));//当类型改变时填充学生privatestaticvoidStudentArvencyDependencyChangedObject(Dependencye){varstudentVm=dasStudentViewModel;如果(d==null)返回;studentVm.PopulateStudents();}publicvoidPopulateStudents(){//Dostuff}//Otherclassstuff...}XAML以上是C#学习教程:在Silverlight中从xaml传递参数到构造函数的所有内容分享,如果对大家有用,需要了解更多C#学习教程,希望大家多多关注——本文来自网络收集,不代表表态,如涉及侵权,请点击右侧联系管理员删除如转载请注明出处: