如何将绑定从父元素中继到子元素的数据上下文?
我有一个场景,在视图中 TabControl 的 TabItem 上有用户控件。这些用户控件分别绑定到 ViewModel 中的单独对象。我需要的是这些控件传递到它们的绑定对象,即父 TabItem 的 IsSelected 属性值。
关于如何进行这种中继绑定有什么想法吗?
I have a scenario where I have user controls on TabItem of a TabControl in the view. These user controls are individually bound to separate objects in the ViewModel. What I need is these controls to pass through to their bound object, the IsSelected property value of the parent TabItem.
Any ideas on how to do this kind of relay binding?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么不让您的
ParentViewModel
跟踪 TabControl 的SelectedIndex
,而不是跟踪各个IsSelected
值?如果这不起作用,通常我会使用 Microsoft PRISM 的 EventAggregator 或 MVVM Light 的 Messenger 之类的东西向其他感兴趣的 ViewModel 广播消息。
在此示例中,我仍然会将
SelectedIndex
绑定到ParentViewModel
中的某些内容,并且每当发生更改时,我都会广播SelectedTabChanged
消息。对此类信息感兴趣的各个子 ViewModel 将订阅这些消息,并根据所选选项卡是否属于它们所属的选项卡来执行所需的任何逻辑。Why not have your
ParentViewModel
track theSelectedIndex
of the TabControl, instead of tracking individualIsSelected
values?If that doesn't work, usually I use something like Microsoft PRISM's
EventAggregator
or MVVM Light'sMessenger
to broadcast messages to other interested ViewModels.In this example, I would still bind the
SelectedIndex
to something in theParentViewModel
, and anytime that changes I would broadcast aSelectedTabChanged
message. The individual child ViewModels that are interested in such information would subscribe to these messages, and perform whatever logic was needed based on if the selected tab is the one they belong to.