WPF Treeview 上下文菜单 IsChecked 绑定 MVVM
我有一个与 ContextMenu 关联的 TreeView。该上下文菜单有一个项目,我想将其 IsChecked 属性绑定到我的 ViewModel。由于我使用的是树,每个树项都绑定到我的 ViewModel 的子属性。
在 VS2010 输出窗口中,我看到此数据绑定错误:
BindingExpression 路径错误:在“对象”“HostMgmtViewModel”(HashCode=12565727) 上找不到“IsAutoStart”属性。 BindingExpression:Path=IsAutoStart; DataItem='HostMgmtViewModel'
这清楚地表明它正在尝试绑定到我的 ViewModel 而不是树项的关联数据。如何绑定到正确的对象?请记住,我的上下文菜单与整个 TreeView 相关联,而不是与特定的树项相关联。
---------- 编辑
正如 xandy 在下面指出的那样,我的问题的解决方案是像这样绑定 IsChecked:
{Binding Path=PlacementTarget.SelectedItem.IsDisabledStart, Mode=OneWay, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}
I've got a TreeView to which I associate a ContextMenu. That contextmenu has an item whose IsChecked property I want to bind to my ViewModel. Since I am using a tree each treeitem is bound to a subproperty of my ViewModel.
In the VS2010 output window I am seeing this databinding error:
BindingExpression path error: 'IsAutoStart' property not found on 'object' ''HostMgmtViewModel' (HashCode=12565727)'. BindingExpression:Path=IsAutoStart; DataItem='HostMgmtViewModel'
This clearly shows it is trying to bind to my ViewModel and not to the treeitem's associated data. How do I bind to the correct object? Remember my contextmenu is associated with the whole TreeView not to the specific treeitem.
---------- Edit
As xandy pointed out below the resolution to my problem was to bind the IsChecked like this:
{Binding Path=PlacementTarget.SelectedItem.IsDisabledStart, Mode=OneWay, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是我的工作代码片段。由 [this] 提供。 1 您所需要的只是更改标签中的绑定路径。我目前正在将 Treeview 绑定到字典,因此它是它的 Key 属性。它在绑定到任何对象集合时不应该有任何问题。一个有趣的发现是上下文菜单不属于元素树的一部分,这导致了问题。我可以毫无问题地绑定文本框:
但是如果对于 menuitem,如果我输入相同的内容,它就不起作用。
This is the working code snippet I have. Courtesy of [this].1 All you need is to change the binding path in the tag. I am currently binding the Treeview to a dictionary, so it is the Key property of it. It should not have any problem in binding to any object collections. One interesting finding is context menu is not in part of element tree and this cause the problem. I could bind the text box with no problem:
But it is not functioning if for menuitem if I put the same thing.