问题
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