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

本文关键字:参数 构造函数 Silverlight 中从 xaml | 更新日期: 2023-09-27 18:02:52

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

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

这是类的构造函数:

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

同样,这里是错误:

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

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

您只能使用默认的无参数构造函数实例化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

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