2015-06-15 70 views
4

我試圖按照答案provided in this post,但我必須錯過一些微不足道的東西。我定義我的DataTemplate S作爲App.xaml如下:使用MVVM的WPF導航

<Application.Resources> 
    <DataTemplate DataType="{x:Type vm:BlowerViewModel}"> 
     <v:BlowerView /> 
    </DataTemplate> 
    <DataTemplate DataType="{x:Type vm:HomeViewModel}"> 
     <v:HomeView /> 
    </DataTemplate> 
</Application.Resources> 

然後,在我的MainWindow.xaml我已經定義了下面的代碼:

<Window x:Class="App.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:vm="clr-namespace:App.UI.ViewModel" 
     Title="MainWindow" SizeToContent="WidthAndHeight"> 
    <Window.DataContext> 
     <vm:MainViewModel /> 
    </Window.DataContext> 
    <ContentControl Content="{Binding CurrentView}" /> 
</Window> 

MainViewModel的代碼包含一個屬性CurrentViewICommand所以我可以切換視圖。定義如下:

public class MainViewModel : BaseViewModel 
{ 
    private BaseViewModel _currentView; 

    public MainViewModel() 
    { 
     CurrentView = new HomeViewModel(); 
    } 

    public BaseViewModel CurrentView 
    { 
     get { return _currentView; } 
     set 
     { 
      if (_currentView != value) 
      { 
       _currentView = value; 
       RaiseChangedEvent("CurrentView"); 
      } 
     } 
    } 

    public ICommand SwitchView { 
     get { 
      return new CommandHandler(() => SwitchBlower()); 
     } 
    } 

    protected void SwitchBlower() 
    { 
     CurrentView = new BlowerViewModel(); 
    } 
} 

在我HomeView.xaml,我已經定義了一個按鈕鏈接到MainViewModel執行SwitchView ICommand。如下所示。

<UserControl x:Class="App.UI.View.HomeView" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:vm="clr-namespace:App.UI.ViewModel" 
     Height="300" Width="300"> 
    <Grid> 
     <TextBlock>This is the homeview</TextBlock> 
     <Button Command="{Binding DataContext.SwitchView, RelativeSource={RelativeSource AncestorType={x:Type vm:MainViewModel}}, Mode=OneWay}" Content="Test" /> 
    </Grid> 
</UserControl> 

當我啓動應用程序時,它沒有註冊事件,點擊按鈕不會觸發事件來改變視圖。我已經嘗試在ICommand get和函數調用本身中加入斷點。起初,我想也許我需要來定義我的數據模板MainViewModel,但這樣做在下面的錯誤結果(即使該項目構建罰款)

不能把窗口的風格

任何人都可以提供我需要得到這個工作缺少的一塊?

+1

AncestorType應該是MainWindow而不是MainViewModel。 MainViewModel不是可視樹的一部分。匆匆一瞥,其他一切看起來都很好。 –

+0

@LeeO。如果您想將其作爲答案發布,我會很樂意將其標記爲已接受。看起來這是我的隧道視野案例!謝謝一堆。 – entropic

+0

看起來你現在全部排序,做得很好。 – Sheridan

回答

3

AncestorType應該是MainWindow而不是MainViewModel。 MainViewModel不是可視樹的一部分。