如何为 Windows 运行时编写装饰器 XAML 自定义控件
本文关键字:XAML 自定义控件 Windows 运行时 | 更新日期: 2023-09-27 18:31:14
WPF 具有可以包含单个子元素的装饰器类。
Windows 运行时没有装饰器类,但具有类似的 Border 类,该类也可以包含子元素。不幸的是,边境类是密封的。
我可以从 Control 派生,并为我的孩子编写一个带有 ContentPresenter 的 ControlTemplate。
边界类是如何编写的?这是我的例子,它不起作用。
[ContentProperty(Name = "Child")]
public class TextBlockDecorator : FrameworkElement
{
public static readonly DependencyProperty ContentProperty = DependencyProperty.Register(
"Child", typeof(TextBlock), typeof(TextBlockDecorator), new PropertyMetadata(null));
public TextBlock Child
{
get { return (TextBlock)GetValue(ContentProperty); }
set { SetValue(ContentProperty, value); }
}
}
当我使用它时,未显示子文本块。如何将其作为子项添加到我的装饰器元素中?我想,我错过了一些像AddVisualChild这样的电话......或类似
Windows::UI::Xaml 没有 WPF 那样的装饰器概念。装饰层是 WPF 独有的,未在其他 Xaml 框架(如 Silverlight 和 Windows::UI::Xaml)中实现。您可以创建一个包含一个或多个子控件并围绕它们绘制的控件,但不能像 Windows::UI::Xaml::Controls::Border 那样执行此操作。边框是框架元素而不是控件,并且没有对所需呈现的外部访问。
为了供您使用,我将创建一个派生自 ContentControl 的自定义控件,然后编辑模板以显示所需的修饰。通过使用 ContentControl 和 ContentPresenter,您可以对任何内容使用相同的"装饰器",而不是将其硬编码为 TextBlocks。
这是一个快速演示,在四个角放了一个圆圈:
Xaml:
<Style TargetType="local:Decorator" >
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:Decorator">
<Grid
Background="{TemplateBinding Background}"
MinHeight="30"
>
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" Margin="5"/>
<Ellipse Height="10" Width="10" Fill="{TemplateBinding Background}" Stroke="{TemplateBinding Foreground}" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<Ellipse Height="10" Width="10" Fill="{TemplateBinding Background}" Stroke="{TemplateBinding Foreground}" HorizontalAlignment="Left" VerticalAlignment="Bottom"/>
<Ellipse Height="10" Width="10" Fill="{TemplateBinding Background}" Stroke="{TemplateBinding Foreground}" HorizontalAlignment="Right" VerticalAlignment="Top"/>
<Ellipse Height="10" Width="10" Fill="{TemplateBinding Background}" Stroke="{TemplateBinding Foreground}" HorizontalAlignment="Right" VerticalAlignment="Bottom"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
代码(与模板化控件模板相同):
public sealed class Decorator : ContentControl
{
public Decorator()
{
this.DefaultStyleKey = typeof(Decorator);
}
}