Alecu
Alecu

Reputation: 2708

Windows phone custom user control with template support

I am making a custom user control and I want the control to be reusable and a part of the control to be usable for adding new controls. What I am trying to make is a template in the custom user control in which the user can add new content.

I am using windows phone 8

How can I do this?

Upvotes: 1

Views: 854

Answers (1)

fex
fex

Reputation: 3558

Add new Templated Control from "Add new item" menu. You should get Generic.xaml file in Themes folder.

In Generic.xaml you have style for your custom control:

<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>

You'll also have .cs file for your custom control. To use controls (in code) from your custom control template xaml you need to use [TemplatePart] attribute on your "control class". Snippet:

[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();
    }
}

Additionaly I have shown you how to expose properties on your control (so your control user can write <namespace:SuperControl IsFancyLookEnabled="True">). You create dependency property (as shown in code snippet) which you can use in your xaml with TemplateBinding - or just use in code.

Upvotes: 4

Related Questions