tags:

views:

127

answers:

2

I need to set a control's background to the color of the parent's background in XAML. Why not simply make the background transparent? It's a button with a drop shadow, so I need to set the background; otherwise, the drop shadow shows through.

So, from my control's markup, how do I set the Background property equal to whatever the parent (host) Background is? Thanks for your help.

+2  A: 

You should be able to set the binding using:

<Button Background="{Binding Path=Background, RelativeSource={RelativeSource Mode="FindAncestor" AncestorType="{x:Type Control}" AncestorLevel="1"}}" />

Since Background is defined for any "Control", this should grab the control one ancestor up the tree, and use it's background.


Another option to consider would be to just make a button style that shows the background as transparent, but actually still draws the drop shadow/border. This would allow it to work on any UIElement.

Reed Copsey
This points at the problem, by the way: quite obviously, the parent isn't necessarily a `Control` (could be any random `UIElement`), and therefore need not have a `Background` property in the first place. But it doesn't mean that it won't actually draw one...
Pavel Minaev
Well, unfortunately, only Control has a background - so to bind to the parent's background, you'd have to bind to a Control. That does make this less-than-pefect, though. I'll edit with another option...
Reed Copsey
A: 

I am going to leave Reed's answer as accepted, since it does answer my original question. But I discovered that I actually need to bind to the window in which the button is hosted. Here is markup to do that:

<Button Background="{Binding Path=Background, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}">My Button</Button>
David Veeneman