C# 如何为Windows运行时编写Decorator XAML自定义控件?
WPF有一个Decorator类,它可以包含一个子元素 Windows运行时没有Decorator类,但有类似的Border类,也可以包含子元素。不幸的是,边境班被封了 我可以从控件派生并使用ContentPresenter为我的孩子编写一个ControlTemplate 边界类是如何编写的?这是我的例子,它不起作用C# 如何为Windows运行时编写Decorator XAML自定义控件?,c#,windows-runtime,winrt-xaml,C#,Windows Runtime,Winrt Xaml,WPF有一个Decorator类,它可以包含一个子元素 Windows运行时没有Decorator类,但有类似的Border类,也可以包含子元素。不幸的是,边境班被封了 我可以从控件派生并使用ContentPresenter为我的孩子编写一个ControlTemplate 边界类是如何编写的?这是我的例子,它不起作用 [ContentProperty(Name = "Child")] public class TextBlockDecorator : FrameworkElement {
[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独有的,在Silverlight和Windows::UI::Xaml等其他Xaml框架中没有实现。您可以创建一个包含一个子控件(或多个子控件)并在其周围绘制的控件,但不能完全像Windows::UI::Xaml::controls::Border那样进行创建。Border是一个FrameworkElement而不是一个控件,并且没有对所需渲染的外部访问 为了便于使用,我将创建一个从ContentControl派生的自定义控件,然后编辑模板以显示所需的装饰。通过使用ContentControl和ContentPresenter,您可以对任何内容使用相同的“装饰器”,而不是将其硬编码为文本块 下面是一个快速演示,在四个角处放置一个圆: 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);
}
}