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

}

}

}

相关推荐
Magnum Lehar4 小时前
wpf游戏引擎前端的Transform.cs实现
前端·游戏引擎·wpf
@Crazy Snail6 小时前
WPF数据绑定疑惑解答--(关于控件的Itemsource,Collection绑定)
windows·wpf·wpf数据绑定
猕员桃7 小时前
《Elasticsearch 分布式搜索在聊天记录检索中的深度优化》
分布式·elasticsearch·wpf
Magnum Lehar8 小时前
wpf3d游戏引擎前端ControlTemplate实现
前端·游戏引擎·wpf
天蓝蓝的本我1 天前
WPF加载文本文件时如何设置WebBrowser的字体
wpf
界面开发小八哥1 天前
界面控件DevExpress WPF v24.2新版亮点:报表等组件功能升级
ui·.net·wpf·界面控件·devexpress·ui开发
苜柠1 天前
WPF案例展示
wpf
Magnum Lehar2 天前
wpf3d游戏引擎下的AssetRegister.cs实现
游戏引擎·wpf
十年一梦实验室2 天前
【AI解析】 WPF 应用程序控制桌面机械臂
wpf
Magnum Lehar2 天前
wpf游戏引擎的Components的entity组件实现
游戏引擎·wpf