MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to create a custom control in XAML and C#

In this article we will learn about XAML & C# and how they can be used to create a custom control.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

What is XAML?

XAML stands for Extensible Application Markup Language. It is an XML-based markup language which is developed by Microsoft. It is generally used for initializing structured values and objects. It is used for various applications which include .Net Framework, Windows Presentation Foundation and many more.

What is C#?

C# is a programming language which is pronounced commonly as C sharp. It consists of imperative, declarative, functional, generic, object-oriented (class-based), and component-oriented programming disciplines. It is a very simple, modern, general-purpose, object-oriented programming language.

Now we will learn how these two languages can be used to build a custom control. As we know, that the flexibility the platform provides to create custom control is the most powerful feature of the Windows 8 XAML platform which provide features like Dependency Properties and Control Templates.

A Simple XAML control

Initially, the Hello world of controls is created. It is a class that is derived from Windows.UI.XAML.Controls.Control. After this, follow the following steps:

  • Firstly, create a new project in Visual Studio. This project should be created by using the Blank Project Template.
  • Secondly, name the project as Custom Controls.
  • Finally, the required customs are added by using the New Item template wizard.
Shows the template for adding New Item

Figure 1: Shows the template for adding New Item.

Shows Template Control item

Figure 2: Shows Template Control item

Listing 1: Shows the code for class created by template.

public class HelloWorld : Control
{
    public HelloWorld()    {
        this.DefaultStyleKey = typeof(HelloWorld);
    }
}

In these codes, two important things are specified. They are as follows:

  • Firstly, the HelloWorld class that is derived from Control.
  • Secondly, setting DefaultStyleKey indicates to the XAML platform that this class uses an implicit style.

This control template adds a folder named themes and also creates a new file named Generic.xaml. In this file, a control’s default style is defined that platform loads automatically. In this file, an implicit file is defined which means that there will be one style that will be applied by default to all controls of a specific type.

Listing 2: Shows the code to define a control’s default style.

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/XAML/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/XAML"
    xmlns:local="using:CustomControls">

    <Style TargetType="local:HelloWorld">
        <Setter Property="VerticalAlignment" Value="Center" />
        <Setter Property="HorizontalAlignment" Value="Center" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:HelloWorld">
                    <Border
                       Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                        <TextBlock Text="HelloWorld" 
                               FontFamily="Segoe UI Light"
                               FontSize="36"/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style> 
</ResourceDictionary>

The next step is to add the next markup by going to the MainPage.xaml file. The “local:” designation must be included in order to let XAML know in which namespace to find the HelloWorld class and it is defined at the top of the XAML file.

Listing 3: Shows the code to define the “local:” designation.

<local:HelloWorld />

Now, after doing this when we run our application we will find that the controls are loaded.

Describing Control Options

After adding configurable options to these controls, they become more useful and reusable. To add the option for the control to blink, we need to add a Dependency Property to the control. It can be added with the help of cursor which is located below the constructor, by typing “propdp” and pressing Tab twice.

Listing 4: Shows the code to add Dependency Property.

public class HelloWorld : Control
{
    public HelloWorld()    {
        this.DefaultStyleKey = typeof(HelloWorld);
    }

    public bool Blink
    {
        get { return (bool)GetValue(BlinkProperty); }
        set { SetValue(BlinkProperty, value); }
    }

    // Using a DependencyProperty enables animation, styling, binding, etc.
    public static readonly DependencyProperty BlinkProperty =
        DependencyProperty.Register(
            "Blink",                  // The name of the DependencyProperty
            typeof(bool),             // The type of the DependencyProperty
            typeof(HelloWorld),       // The type of the owner of the DependencyProperty
            new PropertyMetadata(     // OnBlinkChanged will be called when Blink changes
                false,                // The default value of the DependencyProperty
                new PropertyChangedCallback(OnBlinkChanged)
            )
        );

    private DispatcherTimer __timer = null;
    private DispatcherTimer _timer
    {
        get
        {
            if (__timer == null)
            {
                __timer = new DispatcherTimer();
                __timer.Interval = new TimeSpan(0,0,0,0,500); // 500 ms interval
                __timer.Tick += __timer_Tick;
            }

            return __timer;
        }
    }

    private static void OnBlinkChanged(
        DependencyObject d,
        DependencyPropertyChangedEventArgs e
    )
    {
        var instance = d as HelloWorld;
        if (instance != null)
        {
            if (instance._timer.IsEnabled != instance.Blink)
            {
                if (instance.Blink)
                {
                    instance._timer.Start();
                }
                else
                {
                    instance._timer.Stop();
                }
            }
        }
    }

    private void __timer_Tick(object sender, object e)
    {
        DoBlink();
    }

    private void DoBlink()
    {
        this.Opacity = (this.Opacity + 1) % 2;
    }
}

After this, the configuration option must be added to the control in the MainPage.xaml.

Listing 5: Shows the code to add the configuration option.

<local:HelloWorld Blink="True" />

Adding Support for Events

This feature allows for increasing functionality and allows getting interrupts from the control when actions take place, and then you can run code that reacts to the actions.

Listing 6: Shows the code to add an event for each time the control blinks.

public class HelloWorld : Control
{
    
    ...
...
    private void __timer_Tick(object sender, object e)
    {
        DoBlink();
    }

    private void DoBlink()
    {
        this.Opacity = (this.Opacity + 1) % 2;
        OnBlinked();
    }

    public event EventHandler Blinked;

    private void OnBlinked()
    {
        EventHandler eh = Blinked;
        if (eh != null)
        {
            eh(this, new EventArgs());
        }
    }
}

Now back in the MainPage.xaml, name property is added to retrieve the control instance.

Listing 7: Shows the code to retrieve the control instance in codes.

<local:HelloWorld x:Name="HelloWorldWithEvents" Blink="True" />

After this, an event listener function delegate is added to print debug output when the event is fired.

Listing 8: Shows the code to add an event listener function delegate.

HelloWorldWithEvents.Blinked += (object sender, EventArgs args) =>
{
    System.Diagnostics.Debug.WriteLine("HelloWorldWithEvents Blinked");
};

After running this code, we get to see a message repeating fastly to the Output Console window in Visual Studio.

Conclusion

At the end, we have learnt about the basic languages i.e., XAML and C# and their use in creating the custom controls. We have worked on describing control options and adding support for events.



I am well versed with Computer Programming languages and possess good working knowledge on software languages such as C, Java, PHP, HTML and CSS

What did you think of this post?
Services
Know how to keep MrBool Online
SUPPORT US
SUPPORT US
With your help, we can keep providing free content and helping you to be a better professional
support us
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login