using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using HandyControl.Data; using HandyControl.Interactivity; using HandyControl.Tools; namespace HandyControl.Controls { /// public class TextBox : System.Windows.Controls.TextBox, IDataInput { public TextBox() { CommandBindings.Add(new CommandBinding(ControlCommands.Clear, (s, e) => { SetCurrentValue(TextProperty, ""); })); } protected override void OnTextChanged(TextChangedEventArgs e) { base.OnTextChanged(e); VerifyData(); } public Func> VerifyFunc { get; set; } /// /// 数据是否错误 /// public static readonly DependencyProperty IsErrorProperty = DependencyProperty.Register( "IsError", typeof(bool), typeof(TextBox), new PropertyMetadata(ValueBoxes.FalseBox)); public bool IsError { get => (bool) GetValue(IsErrorProperty); set => SetValue(IsErrorProperty, value); } /// /// 错误提示 /// public static readonly DependencyProperty ErrorStrProperty = DependencyProperty.Register( "ErrorStr", typeof(string), typeof(TextBox), new PropertyMetadata(default(string))); public string ErrorStr { get => (string) GetValue(ErrorStrProperty); set => SetValue(ErrorStrProperty, value); } /// /// 文本类型 /// public static readonly DependencyProperty TextTypeProperty = DependencyProperty.Register( "TextType", typeof(TextType), typeof(TextBox), new PropertyMetadata(default(TextType))); public TextType TextType { get => (TextType) GetValue(TextTypeProperty); set => SetValue(TextTypeProperty, value); } /// /// 是否显示清除按钮 /// public static readonly DependencyProperty ShowClearButtonProperty = DependencyProperty.Register( "ShowClearButton", typeof(bool), typeof(TextBox), new PropertyMetadata(ValueBoxes.FalseBox)); public bool ShowClearButton { get => (bool) GetValue(ShowClearButtonProperty); set => SetValue(ShowClearButtonProperty, value); } public virtual bool VerifyData() { OperationResult result; if (VerifyFunc != null) { result = VerifyFunc.Invoke(Text); } else { if (!string.IsNullOrEmpty(Text)) { if (TextType != TextType.Common) { result = Text.IsKindOf(TextType) ? OperationResult.Success() : OperationResult.Failed(Properties.Langs.Lang.FormatError); } else { result = OperationResult.Success(); } } else if (InfoElement.GetNecessary(this)) { result = OperationResult.Failed(Properties.Langs.Lang.IsNecessary); } else { result = OperationResult.Success(); } } IsError = !result.Data; ErrorStr = result.Message; return result.Data; } } }