我想打電話從兩個不同的視圖模式相同的命令,但在他們的設計(包括命令和視圖模型)我被困命令和的ViewModels關係。WPF:在MVVM
首先,我創建了一個ViewModel1
視圖模型類:
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
命令類:
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();
}
}
然後,我所創建的第二視圖模型類ViewModel2
,但是當我意識到該視圖模型還需要使用相同的命令,該命令的構造
public ProcessMyString(ViewModel1 viewModel)
不會工作,因爲它需要ViewModel1
參數,我需要能夠通過兩種視圖模式。然後,我決定創建ViewModelBase
類,並使兩個視圖模型都從中擴展。我修改了命令的構造,以及,當然:
// Constructor's parameter is now ViewModelBase
public ProcessMyString(ViewModelBase viewModel)
但是,這意味着該命令的方法Execute(object parameter)
從ViewModelBase
稱爲方法了。這不是一個好appproach因爲視圖模型對ProcessMyString()
調用應該是保留只有ViewModel1
和ViewModel2
類。如果我有ViewModel3
課程,我不希望它叫ProcessMyString()
,如果我沒有從ViewModelBase
延伸它會很好。
但是如果我需要在ViewModel2
和ViewModel3
之間共享的命令,會發生什麼?
總和的問題是:我應如何組織命令和視圖模型,以便能夠使視圖車型共享相同的命令?
,如果我要設計出命令的'CanExecute'方法會發生什麼?這個框架有可能嗎? (我有一堆其他命令實際上有'CanExecute'中的一些內容,並不總是返回'true',如我的'ProcessMyString'命令所示。) – Boris 2011-04-09 15:36:54
@Boris是的,這是可能的,這個委託作爲第二個參數。我沒有在我的例子中傳遞任何東西,它有隱含的值'()=> true'。此外,MVVM Light還有另一個使用CommandParameter的命令類。您可以在下載此框架後自行檢查。 – vorrtex 2011-04-09 17:13:47
明白了,謝謝! – Boris 2011-04-09 17:19:48