【问题标题】:Navigation between page页面间导航
【发布时间】:2016-10-08 15:51:57
【问题描述】:

我正在编写一个只有 3 页的小型 WPF 应用程序(目前)。我在主窗口中使用 DataTemplate 和 ContentControl 来显示和切换我的页面。 (参见下面的代码示例)。它正在工作,但我有一些担忧:

  1. DataTemplate 仅使用无参数构造函数。如果我添加一个然后它找不到构造函数。

  2. “注册”在 xaml 中完成,我无法使用依赖注入将视图与 ViewModel 链接起来。

问题:

有没有办法在不使用第三方工具的情况下改变它?

如果唯一好的选择是使用工具,我应该考虑哪些?

<Window.Resources>
    <DataTemplate DataType="{x:Type pageViewModels:HomePageViewModel}">
        <pageViews:HomePageView />
    </DataTemplate>
    <DataTemplate DataType="{x:Type pageViewModels:GamePageViewModel}">
        <pageViews:GamePageView />
    </DataTemplate>
</Window.Resources>

<DockPanel>
    <Border DockPanel.Dock="Left" BorderBrush="Black" BorderThickness="0,0,1,0">
        <ItemsControl ItemsSource="{Binding PageViewModels}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Button Content="{Binding Name}"
                            Command="{Binding DataContext.ChangePageCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
                            CommandParameter="{Binding }"
                            Margin="2,5"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Border>

编辑 为了澄清,我想在我的viewsModels的构造函数中注入一个类,但是如果我这样做了,那么我的应用程序中的导航就会被破坏,因为dataTemplate正在寻找无参数的构造函数。

【问题讨论】:

  • 不清楚的问题。你想达到什么目的?
  • 我正在尝试在我的 viewModel 的构造函数中注入另一个类,但我不能,因为 xaml 中的声明使用的是无参数构造函数。我想找到一种方法来解决上面列出的 1) 和 2) 点。
  • 视图模型的创建应由其他视图模型(或进入应用程序时的应用初始化程序)处理。您的所有视图应该做的是声明它是如何呈现的。到目前为止,这看起来不错。显示更多你的虚拟机代码——你可能只是稍微偏离了模式,因为这对你来说似乎是一个问题:)

标签: c# wpf xaml


【解决方案1】:

看来我的问题在post 中得到了很好的解释。

简而言之,我需要实现一个 ViewModelLocator 模式来解决我的所有顾虑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 2018-06-22
    • 2014-05-16
    • 2021-12-10
    • 2018-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多