There are 3 main steps:
1. First create a custom control that inherits the TextBox
namespace ezintepark.presentation.common{//<summary>//////digital box, inheriting text box, digital input only, extended Value (decimal)//</sum Mary> public class Exnumericbox:textbox {#region Dependency properties public int Digits { get {return (int) GetValue (digitsproperty);} set {SetValue (Digitsproperty, value);} } public static readonly DependencyProperty Digitsproperty = Dependencyproperty.register ("Digits", typeof (int), Typ EOF (Exnumericbox), New PropertyMetadata (2)); Public decimal Value {get {return (decimal) GetValue (valueproperty);} set {SetValue (Valueproperty,value);} } public static readonly DependencyProperty Valueproperty = Dependencyproperty.register ("Value", typeof (decimal), t Ypeof (Exnumericbox), New PropertyMetadata (decimal. Zero)); #endregion public Exnumericbox (): Base () {this. Verticalcontentalignment = Verticalalignment.center This. TextChanged + = new Textchangedeventhandler (numericbox_textchanged); } private String backupstring = ""; <summary>/////</summary>/<param name= "sender" ></param>// /<param name= "E" ></param> private void Numericbox_textchanged (object sender, Textchangedeventargs e) {TextBox TB = (textbox) sender; String temp = tb. Text.trim (); if (!isdecimal (temp)) {//revert string TB. Text = backupstring; Tb. Select (backupstring.length, 0); Return } decimal tempvalue = 0; Decimal.tryparse (temp, out tempvalue); backupstring = temp; Value = Tempvalue; }//<summary>//whether digital///</summary>//<param name= "source" ></param& Gt <returns></returns> BOOLIsdecimal (String source) {foreach (char item in source) {if (item < ' 0 ' || Item > ' 9 ') {if (Digits = = 0) return false; if (Digits! = 0 && Item! = ') return false; }} return true; } }}
2. When you want to use the control in the window or UserControl class, first introduce a namespace, such as:
3. Use the control
<common:exnumericbox x:name= "Tbfirstcost" horizontalalignment= "left" height= "All" margin= "38,4,0,4" TextWrapping= "Wrap" verticalalignment= "center" width= "verticalcontentalignment=" center "grid.column=" 1 "/>
custom controls in WPF and their use