Pages

Monday 25 July 2011

WPF C# IPAddress Control

During my quest to create a customised IP Scanner to use at work, I struggled to find a decent control to handle an IP Address. Some controls on the internet made use of MaskedTextProvider, applying a mask to a TextBox to assist in validating the input. But as you can imaging, that's kinda ugly and crap. So, I decided to take the plunge and create my own IPAddress user control.

In short, the control simply consists of four TextBoxes separated by three Labels containing the decimal separator.

A stripped down example:


    <Border Name="borderMain" BorderThickness="1" BorderBrush="#FFA5ACB2">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="30" />
                <ColumnDefinition Width="3" />
                <ColumnDefinition Width="30" />
                <ColumnDefinition Width="3" />
                <ColumnDefinition Width="30" />
                <ColumnDefinition Width="3" />
                <ColumnDefinition Width="30" />
            </Grid.ColumnDefinitions>
           
            <TextBox Grid.Column="0" TabIndex="0" x:Name="TextOctet1" Text="{Binding Path=Octet1 />

            <TextBlock Grid.Column="1" Text="." Width="5" />

            <TextBox Grid.Column="2" TabIndex="1" x:Name="TextOctet2" Text="{Binding Path=Octet2  />

            <TextBlock Grid.Column="3" Text="." Width="5" />

            <TextBox Grid.Column="4" TabIndex="2" x:Name="TextOctet3" Text="{Binding Path=Octet3 />

            <TextBlock Grid.Column="5" Text="." Width="5" />

            <TextBox Grid.Column="6" TabIndex="3" x:Name="TextOctet4" Text="{Binding Path=Octet4 />

        </Grid>
    </Border>


Altogether, it's pretty simple to create. The code behind just needs to handle validation to keep your input in check and also navigation within the control.

Link to Source and binary: http://dl.dropbox.com/u/26136919/IPAddress.7z

3 comments:

  1. Hi Josh,
    what is the type of license for your code?

    ReplyDelete
  2. No point in a license. Anyone can make this kind of stuff.

    ReplyDelete
  3. I added this dependency property so that the IPAddress is bindable ....


    public static readonly DependencyProperty IPAddressObjectProperty =
    DependencyProperty.Register(
    "IPAddressObject",
    typeof(IPAddress),
    typeof(IPAddressControl),
    new PropertyMetadata(IPAddress.Parse("0.0.0.0"),
    new PropertyChangedCallback(UpdateIPAddressObjectProperty)));


    private static void UpdateIPAddressObjectProperty(DependencyObject ipAddressControl,
    DependencyPropertyChangedEventArgs e)
    {
    (ipAddressControl as IPAddressControl).IPAddressObject = (IPAddress)e.NewValue;
    }

    ReplyDelete