3

Silverlight 対応の WCF サービスからデータを取得し、それを DataGrid ItemSource にバインドしています。しかし、ViewModel のコンストラクターはパラメーターを取得しています。私はMVVMを使用しています。そして、xaml からコンストラクターにパラメーターを渡したいと思います。ここに何を追加する必要がありますか? これは、ページの DataContext を設定している xaml の部分です。

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

そして、これはクラスのコンストラクタです:

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

また、ここにエラーがあります:

型 'StudentViewModel' は、パブリックではないか、パブリックのパラメーターなしのコンストラクターまたは型コンバーターを定義していないため、オブジェクト要素として使用できません。

4

1 に答える 1

5

WPFエラーメッセージが示すように、デフォルトのパラメーターなしのコンストラクターを使用してのみオブジェクトをインスタンス化できます。したがって、最善の策は、「Type」を aDependencyPropertyにしてバインディングを設定し、それが設定されたら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>
于 2013-03-08T15:36:07.480 に答える