Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to customize and implement IP address input Control by WPF

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how WPF customizes the implementation of IP address input control. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

I. Preface

WPF does not have a built-in IP address input control, so we need to define the implementation ourselves.

Let's first take a look at the features of the IP address input control:

Input three numeric focus will move to the right keyboard ←→ can empty cursor move anywhere can copy the entire IP address, and support x.x.x.x format paste assignment delete characters will automatically move the focus to the left

Knowing the above features, we can get started.

II. Composition

Grid+TextBox*4+TextBlock*3

Through the combination of these controls, we complete the function of IP address input control.

The interface code is as follows:

Third, verify the input format

CustomTextBoxTextStyle and validationTemplate styles have been added to the interface for TextBox, which will be applied to the control when the input format is incorrect.

Verify that the format of the input content is required by customizing the rule IPRangeValidationRule.

The custom rule code is as follows:

Public class IPRangeValidationRule: ValidationRule {private int _ min; private int _ max; public int Min {get {return _ min;} set {_ min = value;}} public int Max {get {return _ max;} set {_ max = value;}} public override ValidationResult Validate (object value, CultureInfo cultureInfo) {int val = 0; var strVal = (string) value; try {if (strVal.Length > 0) {if (strVal.EndsWith (".")) {return CheckRanges (".", ")) } / / Allow dot character to move to next box return CheckRanges (strVal);}} catch (Exception e) {return new ValidationResult (false, "Illegal characters or" + e.Message);} if ((val)

< Min) || (val >

Max) {return new ValidationResult (false, "Please enter the value in the range:" + Min + "-" + Max + ".);} else {return ValidationResult.ValidResult;}} private ValidationResult CheckRanges (string strVal) {if (int.TryParse (strVal, out var res)) {if ((res)

< Min) || (res >

Max) {return new ValidationResult (false, "Please enter the value in the range:" + Min + "-" + Max + ".);} else {return ValidationResult.ValidResult;}} else {return new ValidationResult (false," Illegal characters entered ");}

Fourth, control the change of focus

In the interface code, I use local:FocusChangeExtension.IsFocused to attach properties to bind attributes to control the change of focus.

The code for the additional attribute is as follows:

Public static class FocusChangeExtension {public static bool GetIsFocused (DependencyObject obj) {return (bool) obj.GetValue (IsFocusedProperty);} public static void SetIsFocused (DependencyObject obj, bool value) {obj.SetValue (IsFocusedProperty, value);} public static readonly DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached ("IsFocused", typeof (bool), typeof (FocusChangeExtension), new UIPropertyMetadata (false, OnIsFocusedPropertyChanged)); private static void OnIsFocusedPropertyChanged (DependencyObject d, DependencyPropertyChangedEventArgs e) {var control = (UIElement) d; if (bool) e.NewValue {control.Focus ();}

Fifth, VM+ background code mixed to achieve focus control and content copy and paste

1, the background code is mainly to copy and paste content, in addition, ←→ mobile cursor also needs background code control. Use PreviewKeyDown events to capture events such as keyboard moving left and right, copying, deleting, etc., and deal with them accordingly:

Private void Part2_KeyDown (object sender, System.Windows.Input.KeyEventArgs e) {if (e.Key = = Key.Back & & part2.Text = "") {part1.Focus ();} if (e.Key = = Key.Right & & part2.CaretIndex = = part2.Text.Length) {part3.Focus (); e.Handled = true;} if (e.Key = = Key.Left & & part2.CaretIndex = = 0) {part1.Focus (); e.Handled = true } if (e.KeyboardDevice.Modifiers.HasFlag (ModifierKeys.Control) & & e.Key = = Key.C) {if (part2.SelectionLength = = 0) {var vm = this.DataContext as IpAddressViewModel; Clipboard.SetText (vm.AddressText);}

Add paste events through DataObject.AddPastingHandler (part1, TextBox_Pasting). Assign a value to the control.

2. Implement attribute binding notification through ViewModel to control focus change and content assignment.

To implement the binding notification, the ViewModel class needs to implement the methods in the INotifyPropertyChanged interface.

Let's create a new IpAddressViewModel class that inherits INotifyPropertyChanged. The code is as follows:

Public class IpAddressViewModel: INotifyPropertyChanged {public event EventHandler AddressChanged; public string AddressText {get $"{Part1??" 0}. {Part2?? "0"}. {Part3?? "0"}. {Part4?? "0"} ";} private bool isPart1Focused; public bool IsPart1Focused {get {return isPart1Focused;} set {isPart1Focused = value; OnPropertyChanged ();} private string part1; public string Part1 {get {return part1;} set {part1 = value; SetFocus (true, false, false, false); var moveNext = CanMoveNext (ref part1) OnPropertyChanged (); OnPropertyChanged (nameof (AddressText)); AddressChanged?.Invoke (this, EventArgs.Empty); if (moveNext) {SetFocus (false, true, false, false);} private bool isPart2Focused; public bool IsPart2Focused {get {return isPart2Focused;} set {isPart2Focused = value; OnPropertyChanged ();} private string part2; public string Part2 {get {return part2;} set {part2 = value; SetFocus (false, true, false, false); var moveNext = CanMoveNext (ref part2); OnPropertyChanged (); OnPropertyChanged (nameof ()) AddressChanged?.Invoke (this, EventArgs.Empty); if (moveNext) {SetFocus (false, false, true, false);} private bool isPart3Focused; public bool IsPart3Focused {get {return isPart3Focused;} set {isPart3Focused = value; OnPropertyChanged ();}} private string part3; public string Part3 {get {return part3;} set {part3 = value; SetFocus (false, false, true, false); var moveNext = CanMoveNext (ref part3); OnPropertyChanged (); OnPropertyChanged (nameof (AddressText)); AddressChanged?.Invoke (this, EventArgs.Empty) If (moveNext) {SetFocus (false, true);} private bool isPart4Focused; public bool IsPart4Focused {get {return isPart4Focused;} set {isPart4Focused = value; OnPropertyChanged ();}} private string part4; public string Part4 {get {return part4;} set {part4 = value; SetFocus (false, true); var moveNext = CanMoveNext (ref part4); OnPropertyChanged (); OnPropertyChanged (nameof (AddressText); AddressChanged?.Invoke (this, EventArgs.Empty) } public void SetAddress (string address) {if (string.IsNullOrWhiteSpace (address)) return; var parts = address.Split ('.'); if (int.TryParse (parts [0], out var num0)) {Part1 = num0.ToString ();} if (int.TryParse (parts [1], out var num1)) {Part2 = parts [1];} if (int.TryParse (parts [2], out var num2)) {Part3 = parts [2] } if (int.TryParse (parts [3], out var num3)) {Part4 = parts [3];}} private bool CanMoveNext (ref string part) {bool moveNext = false; if (! string.IsNullOrWhiteSpace (part)) {if (part.Length > = 3) {moveNext = true;} if (part.EndsWith (".")) {moveNext = true; part = part.Replace (".");} return moveNext } private void SetFocus (bool part1, bool part2, bool part3, bool part4) {IsPart1Focused = part1; IsPart2Focused = part2; IsPart3Focused = part3; IsPart4Focused = part4;} public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged ([CallerMemberName] string propertyName = null) {PropertyChanged?.Invoke (this, new PropertyChangedEventArgs (propertyName));}}

This is basically done. Generate the control and then reference it in MainWindow.

On "WPF how to customize the implementation of IP address input control" this article is shared here, I hope the above content can be of some help to you, so that you can learn more knowledge, if you think the article is good, please share it out for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report