我正在制作自定义用户控件,我希望控件可以重复使用,并且控件的一部分可用于添加新控件。我想要做的是自定义用户控件中的模板,用户可以在其中添加新内容。
我正在使用Windows Phone 8
我该怎么做?
答案 0 :(得分:4)
从“添加新项目”菜单中添加新的模板化控件。
您应该在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
- 或者只在代码中使用它。