wpf 附加属性样例代码

using System.Windows;

using System.Windows.Controls;

using System.Windows.Input;

using System.Text.RegularExpressions;

namespace zl_screensaver

{

public static class TextBoxExtensions

{

public static readonly DependencyProperty IsNumericProperty =

DependencyProperty.RegisterAttached("IsNumeric", typeof(bool), typeof(TextBoxExtensions),

new PropertyMetadata(false, OnIsNumericChanged));

public static bool GetIsNumeric(DependencyObject obj)

{

return (bool)obj.GetValue(IsNumericProperty);

}

public static void SetIsNumeric(DependencyObject obj, bool value)

{

obj.SetValue(IsNumericProperty, value);

}

private static void OnIsNumericChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)

{

TextBox textBox = d as TextBox;

if (textBox == null) return;

if ((bool)e.NewValue)

{

textBox.PreviewTextInput += TextBox_PreviewTextInput;

DataObject.AddPastingHandler(textBox, OnPaste);

InputMethod.SetIsInputMethodEnabled(textBox, false); // 禁用输入法

}

else

{

textBox.PreviewTextInput -= TextBox_PreviewTextInput;

DataObject.RemovePastingHandler(textBox, OnPaste);

InputMethod.SetIsInputMethodEnabled(textBox, true); // 启用输入法

}

}

private static void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)

{

if (!IsTextNumeric(e.Text))

{

e.Handled = true;

}

}

private static void OnPaste(object sender, DataObjectPastingEventArgs e)

{

if (e.DataObject.GetDataPresent(typeof(string)))

{

string text = (string)e.DataObject.GetData(typeof(string));

if (!IsTextNumeric(text))

{

e.CancelCommand();

}

}

else

{

e.CancelCommand();

}

}

private static bool IsTextNumeric(string text)

{

Regex regex = new Regex("\^0-9+"); // 只允许数字

return !regex.IsMatch(text);

}

}

}

相关推荐
largecode1 天前
座机号码认证如何操作?申请热线实名名片,树立统一官方客服形象
linux·sql·华为·c#·.net·wpf·harmonyos
小满Autumn1 天前
WPF 入门:XAML 语法、布局与数据绑定
microsoft·c#·.net·wpf
小满Autumn1 天前
WPF 进阶:样式、触发器与控件模板
c#·.net·wpf
她说彩礼65万2 天前
WPF视觉树 逻辑树
wpf
贺国亚2 天前
分布式并发
分布式·wpf
Iawfy_2 天前
WPF的ComboBox绑定Enum枚举
wpf
她说彩礼65万2 天前
WPF TemplateBinding
wpf
她说彩礼65万2 天前
WPF 三大模板类型 四大属性名称
wpf
无心水2 天前
金融系统数据一致性之战:联机交易与批量作业的冲突处理完全指南
人工智能·金融·wpf·批量作业·顶尖架构师·联机交易·金融架构师
步步为营DotNet3 天前
深入.NET 11:ASP.NET Core 10 在构建高可用分布式系统的关键技术与实践
asp.net·.net·wpf