What does exactly do

2019-08-26 05:38发布

问题:

While creating a simple custom expander, I encountered the problem where items inside IT wouldn't bind. I found the fix on this link:

http://codeoverload.wordpress.com/2012/03/04/wpf-expander-headertemplates-dont-forget-the-binding/

Which happens to treat that exact same issue, however what I understand from it is "found this by luck, not really sure why it worked ;D"

My question being now: why does adding Header={Binding} fixes the issue. Indeed from the fact binding wouldn't work, it seems it's due to the DataContext, but I don't see how this should fix it.

Thanks for explaining; hopefully this isn't a duplicate >.<

回答1:

From the docs

Gets or sets the data used for the header of each control.

That object being a binding against the DataContext, or plain text, or whatever.

I'd bet the implementation looks to see if the value is text, and if so, throws it into the default header template which could be something as simple as

<TextBlock Text="{Binding}" />

If you declare a template for the header, the DataContext will be whatever you assign to the Header property. The DataContext of the Expander doesn't flow automatically to the header template, apparently.