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

}

}

}

相关推荐
李高钢15 小时前
【WPF】MVVM 与数据绑定实战:从原理到完整项目
wpf
李高钢21 小时前
【WPF】从 Avalon 到 .NET 10:WPF 平台演进史与特性全览
.net·wpf
李高钢2 天前
WPF MVVM Light 入门:从零到Hello World
c#·wpf
李高钢2 天前
WPF MVVM Light(三):RelayCommand 命令与 Messenger 消息
前端·c#·wpf
SamChan903 天前
FastAPI+Celery+Redis搭建企业级PDF翻译异步任务系统
redis·后端·python·pdf·wpf·fastapi
李高钢3 天前
C# WPF Prism 进阶(三):导航(Navigation)深入
开发语言·c#·wpf
李高钢4 天前
C# WPF 的 Prism 框架入门:核心概念与一个完整示例
开发语言·c#·wpf
SamChan904 天前
用Playwright端到端测试PDF翻译功能:Web自动化测试实战
前端·python·ai·pdf·wpf
Now喔4 天前
WPF动画
wpf
FuckPatience6 天前
WPF 给一个界面上的按钮应用同一种样式
wpf