Friday, 15 August 2014

Custom Controls

Custom controls are Normal controls that you've customized, at least that's how I remember them. basically they're controls that you inherit form and extend with your own functionality. so let's make one.

using Windows.UI.Xaml.Controls;

namespace Custom.Controls
{
    class ImageButton : Button
    {
        public Image Image
        {
            get { return base.Content as Image; }
            set {
                this.Content = value;
            }
        }

        public ImageButton(Image Image)
            : base()
        {
            this.Height= 70;
            this.Width = 100;
            this.DefaultStyleKey = typeof(Button);
            this.Image = Image;
        }
    }
}


our custom control above inherits from button, it takes an image in as a parameter in the constructor:
  • set's our image buttons style to that of a regular button 
  • then sets the button's content as that image
and that's it.

Now in our interface.

<Page
    x:Class="Custom.Controls.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Custom.Controls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <StackPanel x:Name="content_SP" VerticalAlignment="Center">
            <Button x:Name="Add_BTN" Content="Add" />
        </StackPanel>
    </Grid>
</Page>


When we click the add button
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;

namespace Custom.Controls
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            this.Add_BTN.Click += Add_BTN_Click;
        }

        void Add_BTN_Click(object sender, RoutedEventArgs e)
        {
            var bitmapImage =
                new BitmapImage(new Uri("ms-appx:///Assets/Logo.png", UriKind.Absolute));

            var img = new Image { Source = bitmapImage };

            this.content_SP.Children.Add(new ImageButton(img));
        }
    }
}

we add our image Button to our stackpanel


pretty straight forward, now in all actuality for something this trivial you really wouldn't create a custom control, you'd probably just make a template and modify the look and feel of the control.