将 Visibilty 与 DataContext 结合使用在 Button 中不起作用
我有一个按钮,我试图在其中添加绑定到特定路径的可见性属性。在大多数情况下,将调用此路径并返回 Visibilty(隐藏或可见)。如果我有一个按钮,将 DataContext 设置为不同的绑定路径并尝试添加可见性内容,则可见性绑定路径永远不会被调用。如果我删除 DataContext 那么可见性工作正常。有什么办法可以解决这个问题吗?为什么会发生这种情况?非常非常感谢。
<Button Visibility="{Binding Path=ThisButtonVisibility}"
DataContext="{Binding Path=ThisButtonDataContext}"
I have a Button where I am trying to add a Visibility attribute which binds to a certain path. In most cases this path will be call and I return a Visibilty(Hidden or Visible). If I have a button that has a DataContext set to a different binded path and try to add the Visiblity stuff, the visibilty binded path never gets called. If I remove the DataContext then the Visibilty works fine. Is there some kind of work around for this? Why does this happen? Thank you very very much.
<Button Visibility="{Binding Path=ThisButtonVisibility}"
DataContext="{Binding Path=ThisButtonDataContext}"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您在按钮上设置 DataContext 并在按钮“内部”进行数据绑定后,绑定是相对于刚刚设置的 DataContext 的。因此它会搜索属性 ThisButtonDataContext.ThisButtonVisibility。
通常,按钮从其父级继承 DataContext,但当您显式设置另一个 DataContext 时,它将不再找到覆盖的 DataContext。
简而言之:数据上下文在元素本身中已经有效,而不仅仅是其内容。
那么你可以做什么:
移动对象 ThisButtonDataContext 中的可见性并且它可以工作
As you set a DataContext on the Button and make after a Databinding "inside" of the button the Binding is relative to the DataContext which just got set. So it searches for the Property ThisButtonDataContext.ThisButtonVisibility.
Normally the Button inherits the DataContext from its parent, but as you set explicit another one it wont find anymore the overlaying DataContext.
So simply said: the datacontext is already valid in the element itself, not just in its content.
So what you can do:
Move the Visibility in the Object ThisButtonDataContext and it works
将您的绑定更改为
Change your binding to
绑定使用 DataContext 作为隐式源。所以你的分配是不正确的,因为 Binding 表达式将查找 DataContext(它是 Binding)到 DataContext 来查找 DataContext(它是 Binding),并且一次又一次......;)
Binding use DataContext as implicit source. So your assignment is incorrect, because Binding expression will look for DataContext which is Binding to DataContext to look for DataContext which is Binding and again and again... ;)