Using Visibilty with DataContext doesn't work in Button

≡放荡痞女 提交于 2019-12-11 23:42:34

问题


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}"

回答1:


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




回答2:


Change your binding to

<Button Visibility="{Binding Path=ThisButtonDataContext.ThisButtonVisibility}"
        DataContext="{Binding Path=ThisButtonDataContext}"



回答3:


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... ;)



来源:https://stackoverflow.com/questions/5155852/using-visibilty-with-datacontext-doesnt-work-in-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!