두 개의 서로 다른 뷰 모델에서 동일한 명령을 호출하려고하는데이를 설계하는 동안 (명령 및 뷰 모델 모두) 멈추었습니다. 나는 것을 깨달았을 때 나는 두 번째 뷰 모델 클래스 ViewModel2
을 만든 다음WPF : MVVM의 명령 및 ViewModels 관계
public class ProcessMyString : ICommand
{
private ViewModel1 viewModel;
public ProcessMyString(ViewModel1 viewModel)
{
this.viewModel = viewModel;
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
viewModel.ProcessMyString();
}
}
:하지만,
public class ViewModel1 : DependencyObject
{
...
// The command property
public ProcessMyString ProcessMyStringCommand { get; set; }
public ViewModel1()
{
// Command gets instantiated
this.ProcessMyStringCommand = new ProcessMyString(this);
}
internal void ProcessMyString()
{
// This is where the actual processing method is called
// somewhere from the business logic...
...
}
그리고 ProcessMyString
명령 클래스 :
첫째, 나는 ViewModel1
뷰 모델 클래스를 생성 이 뷰 모델 도 동일한 명령을 사용해야합니다., 명령의 생성자
public ProcessMyString(ViewModel1 viewModel)
은 ViewModel1
매개 변수를 사용하기 때문에 작동하지 않으며 두 모델 모두를 전달할 수 있어야합니다. 그런 다음 ViewModelBase
클래스를 만들고 두 모델을 모두 확장하도록 결정했습니다. 나는 물론,뿐만 아니라 명령의 생성자를 수정 :
// Constructor's parameter is now ViewModelBase
public ProcessMyString(ViewModelBase viewModel)
하지만 지금은 ViewModelBase
에서하는 방법이라고 Execute(object parameter)
해당 명령의 방법을 의미했다. ViewModel의 ProcessMyString()
에 대한 호출은 이 및 ViewModel2
클래스의 경우에만으로 예약되어야하기 때문에 좋은 appproach가 아닙니다. 만약 내가 ViewModel3
클래스를 가지고 있다면 나는 ProcessMyString()
을 호출하는 것을 원하지 않을 것이고, 그것을 ViewModelBase
에서 연장하지 않는다면 괜찮을 것이다.
그러나 ViewModel2
과 ViewModel3
사이에 공유되는 명령이 필요한 경우 어떻게됩니까?
요약 질문은 다음과 같습니다.보기 명령 모델을 구성하여보기 모델이 동일한 명령을 공유하도록하려면 어떻게해야합니까?
: 여기
단지 내가이 시나리오를 접근하는 방법의 빠른 실행 다운입니까? 이 프레임 워크에서 가능합니까? (실제로'CanExecute'에 어떤 내용을 가지고 있고'ProcessMyString' 명령에서 보았 듯이 항상'true'를 리턴하지는 않는 다른 명령들을 가지고 있습니다.) – Boris
@Boris 예, 가능하며이 대리자는 두 번째로 전달됩니다 매개 변수. 내 예제에서는 아무 것도 전달하지 않았으며 내재 된 값'() => true'를가집니다. 또한 MVVM Light에는 CommandParameter를 사용하는 다른 명령 클래스가 있습니다. 이 프레임 워크를 다운로드 한 후에 직접 확인할 수 있습니다. – vorrtex
감사합니다. – Boris