[英]Windows phone custom user control with template support
我正在制作一个自定义用户控件,我希望该控件可重用,并且该控件的一部分可用于添加新控件。 我要制作的是自定义用户控件中的模板,用户可以在其中添加新内容。
我正在使用Windows Phone 8
我怎样才能做到这一点?
从“添加新项”菜单中添加新的模板化控件。 您应该在Themes
文件夹中获取Generic.xaml
文件。
在Generic.xaml
您具有自定义控件的样式:
<Style TargetType="local:CustomControl1">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:CustomControl1">
Write your control xaml here
<Border x:Name="BorderNameTest"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Button IsEnabled="{TemplateBinding IsFancyLookEnabled}"></Button>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
您还将具有用于自定义控件的.cs
文件。 要使用自定义控件模板xaml中的控件(以代码形式),您需要在“控件类”上使用[TemplatePart]
属性。 片段:
[TemplatePart(Name = BorderTestTemplatePartName, Type = typeof(Border))]
public sealed class CustomControl1 : Control
{
private const string BorderTestTemplatePartName = "BorderNameTest";
private Border _myBorder;
public static readonly DependencyProperty IsFancyLookEnabledProperty = DependencyProperty.Register(
"IsFancyLookEnabled", typeof (bool), typeof (CustomControl1), new PropertyMetadata(default(bool)));
public bool IsFancyLookEnabled
{
get { return (bool) GetValue(IsFancyLookEnabledProperty); }
set { SetValue(IsFancyLookEnabledProperty, value); }
}
public CustomControl1()
{
this.DefaultStyleKey = typeof(CustomControl1);
}
protected override void OnApplyTemplate()
{
_myBorder = GetTemplateChild(BorderTestTemplatePartName) as Border;
// attach events etc. (you can detach them using for example Unloaded event)
base.OnApplyTemplate();
}
}
另外,我向您展示了如何在控件上公开属性(以便控件用户可以编写<namespace:SuperControl IsFancyLookEnabled="True">
)。 您创建了依赖项属性(如代码片段所示),您可以在具有TemplateBinding
的xaml中使用该属性,也可以仅在代码中使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.