[英]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.