MVVMLight 툴킷을 사용하여 WPF 응용 프로그램을 만듭니다. "부모"양식 (ParentView)이 있고 모든 "하위"개체를로드 할 "부모"개체 (부모)를 전달하여 "자식"양식 (ChildView)을로드하려고합니다.ICommand 및 ServiceLocator를 사용하여 Parent 객체를 전달하여 MVVM 방식으로 Child 객체로드
필자는 누군가의 분석에서 중요하다고 생각하는 3 가지 기본 클래스 인 CodeModelLocation, ChildViewModel, ParentViewModel을 포함 시켰습니다. 처음에는 ParentView (아래 참조)를 인스턴스화하여 ParentViewModel 내에서 ICommand 속성을 구현할 생각 이었지만, MVVM 방식으로이 작업을 수행하려고 시도하고 있기 때문에 올바르게 보이지 않습니다. 누군가 다음과 같은 현재 구조를 어떻게 도울 수 있습니까? 어떻게 부모를 자녀에게 전달할 수 있습니까?
// ----- ChildViewModel -----
public class ChildViewModel
{
// this ctor doesn't make sense in the MVVM world, right?...
public ChildViewModel(Parent selectedParent)
{
this.Parent = selectedParent;
// ...
}
// how do I plug into this one?...
public ChildViewModel(IParentService parentService)
{
this.ParentService = parentService
// ...
}
// ... removed other code for brevity
}
// ----- ParentViewModel -----
{
public ICommand ShowChildCommand
{
get { return new RelayCommand(() => new ChildView(SelectedParent).Show()); }
}
// ... removed other code for brevity
}
// ----- ViewModelLocator -----
public class ViewModelLocator
{
public ChildModel ChildViewModel
{
get { return ServiceLocator.Current.GetInstance<ChildViewModel>(); }
}
public ParentModel ParentViewModel
{
get { return ServiceLocator.Current.GetInstance<ParentViewModel>(); }
}
public ViewModelLocator()
{
SimpleIoc.Default.Register<IChildService, ChildService>();
SimpleIoc.Default.Register<IParentService, ParentService>();
// ... removed other code for brevity
SimpleIoc.Default.Register<ChildViewModel>();
SimpleIoc.Default.Register<ParentViewModel>();
}
// ... removed other code for brevity
}
// ------ 개정이 편집 ------------
나는 사용자 @kidshaw의 최신 제안을 포함하지만이에 의해 난처한 상황에 빠진했다 ParentView 내에서 ChildView의 인스턴스를 생성해야만했던 주석. 어떻게해야할지 모르겠다. 메신저에 대한 MSDN 기사를 다시 읽었지 만 그 질문에 어떻게 도움이되는지는 알지 못합니다. 나는 다음의 최신 코드를 포함시켰다. 댓글 섹션을 참조하십시오. 샘플에서
public class ChildViewModel
{
public ChildViewModel(IChildService service)
{
this.ServiceProxy = service;
this.MessengerInstance.Register<ParentViewModel.ParentToChildMessage>(this, this.OnParentToChildMessage);
this.ChildCollection = new ObservableCollection<Child>();
GetChildInfo(this.CurrentParent);
}
}
부모보기에 하위보기의 인스턴스를 만듭니다. xaml 되보기. 나는 부모에게 자식 컨트롤의 인스턴스를 추가하여 동시에 인스턴스가 생성되도록 제안했습니다. – kidshaw