在我的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);
}
}
这不起作用。这是我的问题:为什么?如何使它正常工作?找到祖先是问题所在吗?