我正在制作自定义用户控件,我希望该控件可重复使用,并且希望控件的一部分可用于添加新控件。我想要制作的是自定义用户控件中的一个模板,用户可以在其中添加新内容。
我正在使用 Windows Phone 8
我该怎么做?
请您参考如下方法:
从“添加新项”菜单添加新的模板化控件。 你应该得到 Generic.xaml文件在 Themes文件夹。
在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"> )。您创建依赖属性(如代码片段所示),您可以在 xaml 中使用 TemplateBinding - 或者只是在代码中使用。
