2013-03-12 42 views
0

我有一個窗口,我加載一個UserControl說Control1。現在如果用戶點擊某個按鈕,新的UserControl,Control2應該加載到Window上,並且Control1應該消失。同樣在這裏,當用戶點擊一個按鈕時,下一個UserControl,Control3應該被加載,並且Control2應該消失。應該也可以回去,例如從Control3到Control2。在WPF窗口加載多個UserControls

在我的窗口中加載第一個主UserControl很容易,我已經完成了足夠的工作。但我堅持如何實現用戶控件之間的「導航」。以前從未做過這樣的事情。 我爲我的WPF應用程序使用MVVM。任何一些想法?

Thx。

編輯: 第七季的答案,我現在做的這一個命令切換的控件: 在主窗口:

<DataTemplate DataType="{x:Type ViewModel:MainControlViewModel}"> 
<my:MainControl /> 
</DataTemplate> 
<DataTemplate DataType="{x:Type ViewModel:ProductsControlViewModel}"> 
<my:ProductsControl /> 
</DataTemplate> 


<Grid> 
<ContentControl Content="{Binding CurrentPageViewModel, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> 
</Grid> 

在MainControlViewModel和幾乎相同的ProductsControl:

public ICommand LoadProductControlCommand 
{ 
    get 
    { 
    if (_loadProductControl == null) 
     _loadProductControl = new RelayCommand(LoadProductControl); 
    return _loadProductControl; 
    } 
} 

private void LoadProductControl(object notUsed) 
{ 
    _mainWindowViewModel = (MainWindowViewModel) Application.Current.MainWindow.DataContext; 
    _mainWindowViewModel.CurrentPageViewModel = new ProductsControlViewModel(); 
} 

這是一個好方法還是我應該做不同?因爲在我的應用程序中,按鈕位於控件上而不是主窗口上。

+2

我剛剛[回答](http://stackoverflow.com/a/15365002/302677)幾個小時前關於此主題的另一個問題。它包含一個[鏈接到我的博客](http://rachel53461.wordpress.com/2011/12/18/navigation-with-mvvm-2/),其中包含一些示例代碼,說明如果需要,可以下載。 – Rachel 2013-03-12 16:53:58

+0

@Rachel,我用一些代碼片段編輯了我的問題,我用thx給你。我有這樣的工作。可以在控件命令中更改MainWindowViewModel.CurrentPageViewModel嗎?您博客上的文章指出了我的正確方向。你很聰明,很好看:) 順便說一句,我不能標記你的答案作爲解決方案,因爲你將它添加爲註釋... – PitAttack76 2013-03-12 20:57:01

+0

通常我不喜歡引用像「Application.Current.MainWindow」這樣的UI組件從ViewModel層是可能的。理想情況下,我更願意綁定到ViewModel中的'ICommand'來更改頁面,或者使用某種消息系統來廣播主ViewModel可以訂閱的ChangePage消息。我在我的博客上有一個[簡短的消息系統概述](http://rachel53461.wordpress.com/2011/06/05/communication-between-viewmodels-with-mvvm/) – Rachel 2013-03-13 12:44:05

回答

0

Rachel的評論幫助我找到了解決方案。

0

把一個ContentPresenter這樣在主窗口:

<ContentPresenter Content="{Binding ActiveWidget}"/> 

,然後在視圖模型

public ViewModelBase ActiveWidget {get;set;} // Don't forget INotifyPropertyChanged!! 

,那麼你必須爲每個ViewModel一個DataTemplateUserControl S的一個適當的實例。請參閱This Article以獲得對此的通用解決方案。