In my WPF application I'm trying bind the background colour of a label to the colour of it's ancestor, however the coloured ancestor is couple of levels above.
What I have in my xaml
code is this:
<Grid Background="Ivory" ClipToBounds="True" >
<Canvas x:Name="SignalNames"
Panel.ZIndex="1"
HorizontalAlignment="Left"
Height="{Binding Path=ActualHeight,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Grid}}}" >
<Label Content="TestLabel">
<Label.Background>
<SolidColorBrush Opacity="0.618"
Color="{Binding Path=Background.Color,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Grid}}}" />
</Label.Background>
</Label>
</Canvas>
</Grid>
This works perfectly.
Now, I'd like to achieve the same effect (opaque background of the label) in the code, as I'm planning to place more labels and position them based on some calculated parameters.
I've came up wit the following code:
public class OpaqueLabel : Label
{
public OpaqueLabel(Canvas canvas, string content, double position)
{
this.Content = content;
canvas.Children.Add(this);
Binding b = new Binding();
b.Path = new PropertyPath("Background.Color");
b.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(Grid), 2);
Brush br = new SolidColorBrush();
br.Opacity = 0.618;
this.Background = br;
BindingOperations.SetBinding(br, SolidColorBrush.ColorProperty, b);
this.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
this.Width = this.DesiredSize.Width;
this.Height = this.DesiredSize.Height;
Canvas.SetTop(this, position);
}
}
This is not working. And here comes my question: why? How can I make it working? Is finding the ancestor the problem?