代码之家  ›  专栏  ›  技术社区  ›  aligray

绑定到DataContext外部的属性

  •  0
  • aligray  · 技术社区  · 16 年前

    我正在创建一个WPF应用程序,并且在实现我的用户界面想法时遇到了一些困难。

    我有一个 MasterViewModel 绑定到 MainWindow 它公开了 ViewModels . 我已经编写了一些命令,这些命令基本上转换了可观察集合中的当前视图模型,然后显示了相应的视图。但是,当应用程序首次加载时,我添加了 HomeViewModel 显示主页(导航)视图的集合。我面临的问题是,我所绑定的命令暴露在 主视图模型 所以它们不会“级联”到项控件中。谁能提供解决方案或更好的方案?多谢。

    这是我收到的错误:

    system.windows.data错误:40:
    BindingExpression路径错误:
    在“对象”“homeViewModel”(hashcode=5313339)上找不到“mainWindowViewModel”属性。bindingExpression:path=mainWindowViewModel.loadClientsCommand;
    dataItem='homeViewModel'(hashcode=5313339);
    目标元素是“button”(name='');
    目标属性为“command”(类型为“icommand”)。

    2 回复  |  直到 8 年前
        1
  •  2
  •   Jakob Christensen    16 年前

    我相信您可以通过RelativeSource以以下方式访问MasterViewModel的DataContext上的命令:

    <Button>
        <Button.Command>
            <Binding Path="DataContext.MasterViewCommand">
                <Binding.RelativeSource>
                    <RelativeSource
                        Mode="FindAncestor"
                        AncestorType="{x:Type MasterViewBaseClass}"
                    />
                </Binding.RelativeSource>
            </Binding>
        </Button.Command>
        Click me!
    </Button>
    
        2
  •  1
  •   Community Mohan Dere    9 年前

    您能提供代码场景的代码示例吗?

    1. 这让我想起了乔希·史密斯的MVVM例子。( http://msdn.microsoft.com/en-us/magazine/dd419663.aspx ,mb你从那里得到你的主意了?
    2. 如果我理解正确:为什么不为itemcontrol编写一个vm并将命令放在其中?
    3. 您可以尝试通过relativesource访问itemcontrol中的命令。( How do I use WPF bindings with RelativeSource? )
    推荐文章