Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XAML: Get parent background

Tags:

wpf

xaml

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.

like image 375
David Veeneman Avatar asked Dec 23 '09 17:12

David Veeneman


2 Answers

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.

like image 69
Reed Copsey Avatar answered Sep 22 '22 15:09

Reed Copsey


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>
like image 23
David Veeneman Avatar answered Sep 22 '22 15:09

David Veeneman