我正在尝试创建一个我可以放置的装饰图层,例如通知。我想尽可能地使它成为一般和XAML编写的,所以我创建了一个名为ContentControl
的新AdornerContentControl
,使用如下:
<AdornerDecorator Grid.Row="1" Name="RichTextBoxAdornerDecorator">
<loc:AdornerContentControl x:Name="TestAdorner">
<loc:AdornerContentControl.Decorator>
<Button Width="100" Height="100">ZZZ</Button>
</loc:AdornerContentControl.Decorator>
<RichTextBox>
<!-- some more stuff... -->
</RichTextBox>
</loc:AdornerContentControl>
</AdornerDecorator>
这是代码:
public class AdornerContentControl : ContentControl {
private SimpleAdorner _adorner;
public static readonly DependencyProperty DecoratorProperty = DependencyProperty.Register(
"Decorator", typeof (Control), typeof (AdornerContentControl), new PropertyMetadata(default(Control),
OnDecoratorPropertyChanged));
private static void OnDecoratorPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { /*...*/ }
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
try { _adorner = new SimpleAdorner((UIElement)Content, Decorator); }
catch (NullReferenceException) { }
}
public Control Decorator
{
get { return (Control) GetValue(DecoratorProperty); }
set { SetValue(DecoratorProperty, value); }
}
}
public class SimpleAdorner : Adorner{
public SimpleAdorner([NotNull] UIElement adornedElement, Control content) : base(adornedElement)
{
_visuals = new VisualCollection(this);
_adornerLayer = AdornerLayer.GetAdornerLayer(adornedElement);
if (content == null) return;
_visuals.Add(_contentPresenter = new ContentPresenter()
{
Content = content
});
_adornerLayer.Add(this);
}
}
但AdornerLayer.GetAdornerLayer(adornedElement)
始终返回null
(SimpleAdorner
是在OnInitialized
中构建的。)