Saturday, 4 January 2014

IPAddress Control in WPF

IPAddressControl.xaml Code: 

<UserControl x:Class="IPAddressWPFUserControl.IPAddressControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" BorderThickness="0" OverridesDefaultStyle="False" >    
    <UniformGrid Columns="7" >

        <TextBox Text="1" Grid.Column="0" Grid.Row="0"  Name="txtboxFirstPart" TextChanged="txtbox_TextChanged" MaxLength="3" BorderThickness="0" TabIndex="1" VerticalContentAlignment="Bottom" FontSize="16" PreviewKeyDown="txtboxFirstPart_PreviewKeyDown" PreviewKeyUp="txtboxFirstPart_PreviewKeyUp" />

        <Label Content="." Grid.Column="1" Grid.Row="0"   Name="label1" VerticalContentAlignment="Bottom"  />
        <TextBox Text="2" Name="txtboxSecondPart" Grid.Column="2" Grid.Row="0" MaxLength="3" TextChanged="txtbox_TextChanged" BorderThickness="0" TabIndex="2" VerticalContentAlignment="Bottom" FontSize="16" KeyDown="txtboxSecondPart_KeyDown" PreviewKeyUp="txtboxSecondPart_PreviewKeyUp" />

        <Label Content="." Grid.Column="3" Grid.Row="0" Name="label2" VerticalContentAlignment="Bottom" />
        <TextBox  Text="3" Name="txtboxThridPart" Grid.Column="4" Grid.Row="0" MaxLength="3" TextChanged="txtbox_TextChanged" BorderThickness="0" TabIndex="3" VerticalContentAlignment="Bottom" FontSize="16" KeyDown="txtboxThridPart_KeyDown" PreviewKeyUp="txtboxThridPart_PreviewKeyUp" />

        <Label Content="." Grid.Column="5" Grid.Row="0" Name="label3" VerticalContentAlignment="Bottom" />
        <TextBox Text="4" x:Name="txtboxFourthPart" Grid.Column="6" Grid.Row="0" MaxLength="3" TextChanged="txtbox_TextChanged" BorderThickness="0" TabIndex="4" VerticalContentAlignment="Bottom" FontSize="16"   />

    </UniformGrid>
</UserControl>



IPAddressControl.xaml.cs  Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Text.RegularExpressions;
using IPAddressWPFUserControl.Resources;

namespace IPAddressWPFUserControl
{
    /// <summary>
    /// Interaction logic for IPAddressControl.xaml
    /// </summary>
    public partial class IPAddressControl : UserControl
    {

        #region Constructor

        /// <summary>
        ///  Constructor for the control.
        /// </summary>
        public IPAddressControl()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(IPAddressControl_Loaded);
            // txtboxFirstPart.Text = "0";
        }

        #endregion

        #region Private Variables

        private bool focusMoved = false;

        #endregion

        #region Private Methods

        private static void TextboxTextCheck(object sender)
        {
            TextBox txtbox = (TextBox)sender;
            txtbox.Text = GetNumberFromString(txtbox.Text);
            if (!string.IsNullOrWhiteSpace(txtbox.Text))
            {
                if (Convert.ToInt32(txtbox.Text) > 255)
                {
                    txtbox.Text = "255";
                }
                else if (Convert.ToInt32(txtbox.Text) < 0)
                {
                    txtbox.Text = "0";
                }
            }

            txtbox.CaretIndex = txtbox.Text.Length;
        }

        private static string GetNumberFromString(string str)
        {
            StringBuilder numberBuilder = new StringBuilder();
            foreach (char c in str)
            {
                if (char.IsNumber(c))
                {
                    numberBuilder.Append(c);
                }
            }
            return numberBuilder.ToString();
        }

        #endregion

        #region Private Events

        void IPAddressControl_Loaded(object sender, RoutedEventArgs e)
        {
            txtboxFirstPart.Focus();
        }

        private void txtbox_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                TextboxTextCheck(sender);
            }
            catch (Exception ex)
            {
                throw new Exception(Constants.ErrorGeneralMessage, ex);
            }
        }

        private void txtboxFirstPart_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.OemPeriod)
                {
                    txtboxSecondPart.Focus();
                    focusMoved = true;
                }
                else
                {
                    focusMoved = false;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Constants.ErrorGeneralMessage, ex);
            }

        }

        private void txtboxSecondPart_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.OemPeriod && !focusMoved)
                {
                    txtboxThridPart.Focus();
                    focusMoved = true;
                }
                else
                {
                    focusMoved = false;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Constants.ErrorGeneralMessage, ex);
            }

        }

        private void txtboxThridPart_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.OemPeriod)
                {
                    txtboxFourthPart.Focus();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Constants.ErrorGeneralMessage, ex);
            }
        }

        #endregion

        #region Public Properties
        private string _text;
        /// <summary>
        /// Gets or Sets the text of the control.
        /// If input text is not of IP type type then throws and argument exception.
        /// </summary>
        public string Text
        {
            get
            {
                _text = txtboxFirstPart.Text + "." + txtboxSecondPart.Text + "." + txtboxThridPart.Text + "." + txtboxFourthPart.Text;
                return _text;
            }
            set
            {
                try
                {
                    string[] splitValues = value.Split('.');
                    txtboxFirstPart.Text = splitValues[0];
                    txtboxSecondPart.Text = splitValues[1];
                    txtboxThridPart.Text = splitValues[2];
                    txtboxFourthPart.Text = splitValues[3];
                    _text = value;
                }
                catch (Exception ex)
                {
                    throw new ArgumentException(Constants.ErrorInputNotIPTypeMessage, ex);
                }
            }
        }
        #endregion

        private void txtboxFirstPart_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                TextBox txtbox = (TextBox)sender;
                if (txtbox.Text.Length == 3)
                {
                    txtboxSecondPart.Focus();
                }
            }
            catch (Exception ex)
            {

            }
        }

        private void txtboxSecondPart_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                TextBox txtbox = (TextBox)sender;
                if (txtbox.Text.Length == 3)
                {
                    txtboxThridPart.Focus();
                }
            }
            catch (Exception ex)
            {

            }
        }

        private void txtboxThridPart_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                TextBox txtbox = (TextBox)sender;
                if (txtbox.Text.Length == 3)
                {
                    txtboxFourthPart.Focus();
                }
            }
            catch (Exception ex)
            {

            }
        }

    }

}








Full screen window in WPF MVVM

Welcome,

To enable full screen window in WPF MVVM Window,  Add this property to the window tag

Width="{DynamicResource {x:Static SystemParameters.FullPrimaryScreenWidthKey}}" Height="{DynamicResource {x:Static SystemParameters.FullPrimaryScreenHeightKey}}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"

PreviewKeyDown and KeyDown event in WPF

PreviewKeyDown used to pre-handle the typed key before it is handled by the KeyDown event.

For Ex: If you want to allow only digits in text dox, then you can use the PreviewKeyDown event this way


        private void ValidateOnTypingTcpPort(object sender, KeyEventArgs e)
        {
            if (!Char.IsDigit((char)KeyInterop.VirtualKeyFromKey(e.Key)) & e.Key != Key.Back & e.Key != Key.Delete & e.Key != Key.Left & e.Key != Key.Right & e.Key != Key.Up & e.Key != Key.Down)
            {
                MessageBox.Show("Provide only digits. Other Keyboard Charrecters are not allowed."); 
                e.Handled = true;
            }
        }


This function will let you input only digits.

Other characters are prevented from appearing in the text box by handling it in the above line e.Handled = true;

This way you can prevent the event to traverse below the tree of controls by making setting its flag as e.Handled = true;

Hide Border, Create Curved Border, Apply Gradient to A Button in WPF

Welcome,

1. Hide Button border in WPF Button Control,  Add below property

Opacity="0.99" Style="{DynamicResource TransperentStyle}"
This is help full in MENU ITEM Creation with button command

2. Make a curved border by applying below property:

Curved Border = "8,8,8,8".

3. Apply Gradient like below


  1:             <Border.BorderBrush>
  2:                 <LinearGradientBrush StartPoint="0,1" EndPoint="1,0">
 3:                     <GradientStop Offset="1" Color="AliceBlue"/>
 4:                     <GradientStop Offset="0" Color="DarkBlue"/>
 5:                 </LinearGradientBrush>
 6:             </Border.BorderBrush>