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

}

}

}

相关推荐
“抚琴”的人4 小时前
C# 取消机制(CancellationTokenSource/CancellationToken)
开发语言·c#·wpf·1024程序员节·取消机制
清风徐来Groot12 小时前
WPF之Style
wpf
rollingman18 小时前
WPF GroupBox 淡入淡出
wpf
yy7634966681 天前
WPF 之 简单高效的Revit多语言支持方案
java·大数据·linux·服务器·wpf
张人玉1 天前
WPF 触发器详解:定义、种类与示例
c#·wpf·1024程序员节·布局控件
rollingman1 天前
WPF ComboBox 样式
wpf·combobox·textbox
Aevget2 天前
DevExpress WPF中文教程:Data Grid - 如何使用虚拟源?(三)
wpf·界面控件·devexpress·ui开发·1024程序员节
张人玉2 天前
WPF 核心概念笔记(补充示例)
c#·wpf·1024程序员节·布局控件
亦陈不染2 天前
WPF-MVVM的简单入门(第一个MVVM程序)
wpf
FuckPatience3 天前
WPF TreeView 条目右键命令 ContextMenu按钮绑定命令
wpf