Click here to Skip to main content
14,355,411 members

IP Address Control using Pure MVVM Pattern with Events

Rate this:
3.09 (8 votes)
Please Sign up or sign in to vote.
3.09 (8 votes)
29 May 2019CPOL
IP Address control using MVVM pattern with auto focus change, various validation and full customization

Introduction

It's always good to look around before starting anything. I had the requirement to create IP Address Control like Windows box. I searched and found many but none of them are complete and breaking MVVM pattern. Most of the logic was handled in code behind of XAML but MVVM says zero line of code in code behind files. So that excited me to move further for creating one. Sharing now with all so that if somebody needs it, they can get the benefit.

Features

The features of this IP Address Control have:

  1. Pure MVVM
  2. Min-Max Validation 0-255. It can be customized.
  3. Highlighting error Red background and "!" if entry is invalid. It can be customized.
  4. ToolTips for the errors
  5. Automatic move to the next box if box has valid entry and limit is reached for that box
  6. '.' Character moves the focus to next box
  7. No third-party dependency

Overview of Functionality in Gif

Features 1 by 1

1. Pure MVVM

No code behind. No View reference in ViewModel. This is very important for the code quality and design.

No Code behind

There is a separate view model IpAddressViewModel which contains all fields or events required for any other view to work in normal cases. The fields are shown below:

Fields of VM

These fields expose all the data required in real time application development.

AddressText is the property that contains the IPAddress entered by User.

2. Min-Max Limits and Number Restrictions

Currently, the limits are set from 0 to 255. These can be customized for each box in control separately.

Lookup of control

Validation only allows number within the range. You can also type "." dot character. The behavior of dot character is described later in this blog.

3. Highlighting Error as Red Background and Exclamation Mark "!"

If any box has any error, then that is highlighted as Red Background, also Red exclamation mark at the end "!".

WARNING:

In real time you might be using either of validation display (Background or Exclamation mark). I kept both validations highlighters for demonstration purpose only.

Highlighted error

The exclamation character can be changed to any character of your choice. In fact, you can use any control of your choice. You just need to play with the below code:

<ControlTemplate x:Key="validationTemplate">
    <DockPanel>
        <TextBlock
            Margin="1,2"
            DockPanel.Dock="Right"
            FontSize="{DynamicResource ResourceKey=Heading4}"
            FontWeight="Bold"
            Foreground="Red"
            Text="!" />
        <AdornedElementPlaceholder />
    </DockPanel>
</ControlTemplate>

To change the highlighting control behavior on error, change the below bold lines code to your choice.

<Style x:Key="CustomTextBoxTextStyle" TargetType="TextBox">
           <Setter Property="MaxLength" Value="3" />
           <Setter Property="HorizontalAlignment" Value="Stretch" />
           <Setter Property="VerticalAlignment" Value="Center" />
           <Style.Triggers>
               <Trigger Property="Validation.HasError" Value="True">
                   <Trigger.Setters>
                       <Setter Property="ToolTip"
                        Value="{Binding RelativeSource={RelativeSource Self},
                        Path=(Validation.Errors)[0].ErrorContent}" />
                       <Setter Property="BorderBrush" Value="Red" />
                       <Setter Property="Background" Value="Red" />
                   </Trigger.Setters>
               </Trigger>
           </Style.Triggers>
       </Style>

4. ToolTips for Errors

There are two types of errors shown below in both the cases we have tooltips to display.

  • Invalid character is entered. This is the case when other than number, any other character is used.

Tooltip display

  • Number is not in defined range, e.g., user enters the out of range number.

Tooltip for display

5. Automatic Move to Next Box

The typing is like Windows IP Address configuration box. This control automatically moves the focus to the next box so that you don't need to move mouse and get the focus. It senses that you have entered valid three characters and then automatically moves the cursor to the next box to type further.

Auto move display in gif

6. Typing the '.' (Dot Character)

Typing the dot character (.) is allowed as it is allowed in windows standard IP address dialogs. The dot character will move the cursor to the next block to type, e.g., the IP Address 127.0.0.1 can be directly typed uninterrupted.

Dot character display in gif

7. No Third Party Dependency

The best thing about this control is, "It is plain WPF". No third-party control/library is used. You can easily customize classes, control, styles and reuse the classes, etc.

Quote:

It is interesting to know "How to manage focus On View from View Model" and "How to put validation rule and control the flow with some exceptional cases".

Fun isn't it. Try it. Look at the code.

Source Code and Demo

Points of Interest

I create only when I don't find anything good. No hobbies of writing! Yes, hobbies are "Code and Learn"!

History

  • Updated as image links were broken after publishing

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Jitendra_Shri
Software Developer (Senior)
India India
No Biography provided

Comments and Discussions

 
QuestionConsider allowing only digits instead of showing tool tip and making validation Pin
Издислав Издиславов16-Jul-19 11:25
memberИздислав Издиславов16-Jul-19 11:25 
QuestionPlease explain where is the event on model and on view? Pin
OriCpp30-May-19 0:16
memberOriCpp30-May-19 0:16 
AnswerRe: Please explain where is the event on model and on view? Pin
Jitendra_Shri1-Jun-19 22:57
memberJitendra_Shri1-Jun-19 22:57 
GeneralRe: Please explain where is the event on model and on view? Pin
OriCpp2-Jun-19 2:55
memberOriCpp2-Jun-19 2:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Article
Posted 28 May 2019

Stats

5.2K views
345 downloads
10 bookmarked