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

}

}

}

相关推荐
@淡 定1 小时前
分布式事务解决方案
分布式·wpf
棉晗榜2 小时前
WPF将程序集里面嵌入的资源文件下载到本机磁盘中,将项目中的文件下载到桌面
开发语言·wpf
△曉風殘月〆3 小时前
WPF MVVM实战系列教程(一、Prism框架介绍)
wpf·mvvm·prism
Aevget4 小时前
DevExpress WPF中文教程:Data Grid - 如何绑定到有限制的自定义服务(三)?
wpf·界面控件·devexpress·ui开发·.net 10
△曉風殘月〆5 小时前
WPF MVVM实战系列教程(二、使用Visual Studio 创建Prism项目)
wpf·mvvm·prism
bugcome_com3 天前
WPF 核心布局控件全解析:从 Grid 到 UniformGrid 的实战应用
c#·wpf
观无3 天前
WPF-Datagrid控件的无缝滚动
wpf
꧁༺℘₨风、凌๓༻꧂3 天前
C# WPF 项目中集成 Pdf查看器
pdf·c#·wpf
Kiyra4 天前
WebSocket vs HTTP:为什么 IM 系统选择长连接?
分布式·websocket·网络协议·http·设计模式·系统架构·wpf