使用 MVVM 的 WPF 导航

ent*_*pic 5 .net c# wpf mvvm

我正在尝试按照这篇文章中提供的答案进行操作,但我一定遗漏了一些微不足道的东西。我将我的DataTemplates定义App.xaml如下:

<Application.Resources>
    <DataTemplate DataType="{x:Type vm:BlowerViewModel}">
        <v:BlowerView />
    </DataTemplate>
    <DataTemplate DataType="{x:Type vm:HomeViewModel}">
        <v:HomeView />
    </DataTemplate>
</Application.Resources>
Run Code Online (Sandbox Code Playgroud)

然后,在我的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>
Run Code Online (Sandbox Code Playgroud)

的代码MainViewModel包含一个属性CurrentView和一个ICommand以便我可以切换视图。定义如下:

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(); 
    }
}
Run Code Online (Sandbox Code Playgroud)

在我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>
Run Code Online (Sandbox Code Playgroud)

当我启动应用程序时,它不会注册事件,并且单击按钮不会触发事件来更改视图。我试过ICommand get在函数调用本身和函数调用本身中放置断点。起初,我想也许我需要MainViewModel在我的数据模板中定义,但这样做会导致以下错误(即使项目构建良好)

无法将 Window 置于样式中

任何人都可以提供我需要让它工作的缺失部分吗?

Lee*_* O. 4

AncestorType 应该是 MainWindow 而不是 MainViewModel。MainViewModel 不是可视化树的一部分的类。