我正在使用MVVM Light的WPF/MVVM應用程序。現在我的ViewModelLocator
是相當標準的;它包含一個static
構造函數,該構造函數通過SimpleIoc
註冊視圖模型,並具有返回視圖模型當前實例的屬性。MVVM中正確使用ViewModelLocator的問題
我不知道這是多麼恰當,但我一直在探索在ViewModels中使用ViewModelLocator
的實例來訪問其他ViewModel的屬性,並在我的某個視圖中更改ContentControl
。如果這樣做有任何重大問題,請讓我知道,以便我能找到解決辦法。例如,我可以在一個視圖模型是這樣的:
private ViewModelLocator _viewModelLocator = new ViewModelLocator();
private void SomeMethod()
{
_viewModelLocator.OtherViewModel.SomeProperty = something;
}
在不同的視圖模型我有以下幾點:
private ViewModelLocator _viewModelLocator = new ViewModelLocator();
public ViewModelBase CurrentViewModel { get; set; }
private void SomeMethod()
{
CurrentViewModel = _viewModelLocator.SomeViewModel;
}
在這種情況下,CurrentViewModel
在我看來綁定到ContentControl
。
目前能夠做到這一點非常方便,但我想從更有經驗的程序員那裏得到一些輸入信息,以確保我不會在自己的腳下射擊。如果有問題,我可以採用更多可以接受的路線來實現相同的結果嗎?
現在,如果有不妥的上述做法,我想知道這是否是合適的和/或可接受,使ViewModelLocator
static
。爲了嘗試一下,我做了一個快速切換到static
ViewModelLocator
。在我MainWindow.xaml,我設置DataContext
到:
DataContext="{Binding Source={x:Static vm:ViewModelLocator.Main}}"
...並回到第一個例子,我可以使用:
private void SomeMethod()
{
ViewModelLocator.OtherViewModel.SomeProperty = something;
}
和:
public ViewModelBase CurrentViewModel { get; set; }
private void SomeMethod()
{
CurrentViewModel = ViewModelLocator.SomeViewModel;
}
目前該程序使用static
ViewModelLocator
可以正常工作,但它還處於初期階段,所以我想知道這是否是未來可行的選擇,或者我應該遠離一共有static
ViewModelLocator
。
任何意見或對這些問題的意見將不勝感激。我對編程還很陌生,我想學習從長遠來看能爲我提供良好服務的技術。
如果我在這裏做的事情沒有明顯的問題,請讓我知道。
謝謝。