2013-03-08 2 views
2

Silverlight 사용 가능 WCF 서비스에서 데이터를 가져 와서 DataGrid ItemSource에 바인딩하고 있습니다. 하지만 내 ViewModel의 생성자가 매개 변수를 가져 오는 중입니다. MVVM을 사용하고 있습니다. 그리고 xaml에서 생성자에 매개 변수를 전달하려고합니다. 여기에 무엇을 추가해야합니까? 이것은 xaml에서 페이지의 DataContext를 설정하는 부분입니다.Silverlight의 xaml에서 생성자에 매개 변수 전달

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

그리고이 클래스의 생성자입니다 : 당신은 기본 매개 변수가없는 사용 WPF에서 개체를 인스턴스화 할 수

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.

답변

5

: 또한

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

, 여기에 오류가 오류 메시지가 나타내는대로 생성자. 따라서 가장 좋은 방법은 '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> 
+0

감사합니다. 그것은 효과가 있었다. –