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);

}

}

}

相关推荐
Zhen (Evan) Wang3 小时前
.NET 6 + Dapper + User-Defined Table Type
sqlserver·c#·.net·wpf
界面开发小八哥1 天前
界面控件DevExpress WPF v25.1预览 - 支持Windows 11系统强调色
windows·wpf·界面控件·devexpress·ui开发·.net 9
军训猫猫头1 天前
89.WPF 中实现便捷的数字输入框:DecimalUpDown 控件的使用 WPF例子 C#例子.
开发语言·c#·wpf
Pasregret1 天前
缓存与数据库一致性深度解析与解决方案
数据库·缓存·wpf
Java林间3 天前
Zookeeper是什么?基于zookeeper实现分布式锁
分布式·zookeeper·wpf
zizisuo3 天前
1.微服务拆分与通信模式
微服务·wpf
程序员秘密基地3 天前
基于c#,wpf,ef框架,sql server数据库,音乐播放器
sql·sqlserver·c#·.net·wpf
Zhen (Evan) Wang3 天前
.NET 6 WPF 利用CefSharp.Wpf.NETCore显示PDF文件
.net·wpf·.netcore
冰茶_4 天前
WPF特性分析
学习·microsoft·c#·wpf
qq_196055875 天前
最快打包WPF 应用程序
wpf