В моем приложении WPF я пытаюсь привязать цвет фона метки к цвету своего предка, однако цветной предок на пару уровней выше.
То, что есть в моем коде xaml
это:
<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>
Это прекрасно работает.
Теперь я хотел бы добиться того же эффекта (непрозрачный фон метки) в коде, как яЯ планирую разместить больше меток и расположить их на основе некоторых рассчитанных параметров.
Я нашел следующий код:
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);
}
}
Это не работает.И вот возникает мой вопрос: почему? Как я могу заставить его работать?Является ли поиск предка проблемой?