gpt4 book ai didi

wpf - 如何告诉我的 DataTemplate 绑定(bind)到 PARENT ViewModel 中的属性?

转载 作者:行者123 更新时间:2023-12-03 08:37:50 25 4
gpt4 key购买 nike

我有以下 MainView.xaml 作为 MVVM 菜单切换器运行良好的文件。我有这些对:

  • Page1View/Page1ViewModel
  • Page2View/Page2ViewModel

  • 在我的 主视图型号 我用两个 ViewModel 填充 ObservableCollection,然后当用户单击 下一个 按钮,它调用 下一页命令 在 MainViewModel 中切换出 CurrentPageViewModel 使用新的 ViewModel,然后使用适当的 View 显示,效果很好。

    我还有一个菜单,其中填充了 Observable 集合中 ViewModels 的所有标题,这也很好用。

    然而,每个 MenuItem 都有一个 Command="{Binding SwitchPageCommand}"应该在 上调用 SwitchPageCommand。主视图型号 而不是例如 第1页查看型号 Page2ViewModel .

    那么如何在模板中指示不绑定(bind)到当前 ViewModel 而是绑定(bind)到包含该 ViewModel 的 ViewModel,例如像这样:
    PSEUDO-CODE:

    <DataTemplate x:Key="CodeGenerationMenuTemplate">
    <MenuItem
    Command="{Binding <parentViewModel>.SwitchPageCommand}"
    Header="{Binding Title}"
    CommandParameter="{Binding Title}"/>
    </DataTemplate>

    这里是 主视图型号 :
    <Window x:Class="TestMenu234.Views.MainView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:c="clr-namespace:TestMenu234.Commands"
    xmlns:vm="clr-namespace:TestMenu234.ViewModels"
    xmlns:v="clr-namespace:TestMenu234.Views"
    Title="Main Window" Height="400" Width="800">

    <Window.Resources>
    <DataTemplate x:Key="CodeGenerationMenuTemplate">
    <MenuItem Header="{Binding Title}" Command="{Binding SwitchPageCommand}" CommandParameter="{Binding Title}"/>
    </DataTemplate>
    <DataTemplate DataType="{x:Type vm:Page1ViewModel}">
    <v:Page1View/>
    </DataTemplate>
    <DataTemplate DataType="{x:Type vm:Page2ViewModel}">
    <v:Page2View/>
    </DataTemplate>
    </Window.Resources>

    <DockPanel>

    <Menu DockPanel.Dock="Top">
    <MenuItem Header="Code _Generation" ItemsSource="{Binding AllPageViewModels}"
    ItemTemplate="{StaticResource CodeGenerationMenuTemplate}"/>
    </Menu>

    <StackPanel DockPanel.Dock="Top" Orientation="Horizontal">
    <Button Margin="5" Content="Next Page" Command="{Binding NextPageCommand}"/>
    </StackPanel>

    <ContentControl
    Content="{Binding CurrentPageViewModel}"/>

    </DockPanel>
    </Window>

    最佳答案

    答案是这样的:

    <DataTemplate x:Key="CodeGenerationMenuTemplate">
    <MenuItem
    Header="{Binding Title}"
    Command="{Binding DataContext.SwitchPageCommand,
    RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Menu}}}"
    CommandParameter="{Binding Title}"/>
    </DataTemplate>

    我刚刚看到 Nir ​​给了我解决上述问题的语法: What is the best way in MVVM to build a menu that displays various pages? .

    关于wpf - 如何告诉我的 DataTemplate 绑定(bind)到 PARENT ViewModel 中的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1026342/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com