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

}

}

}

相关推荐
c#上位机2 小时前
wpf之TabControl
c#·wpf
mingupup2 小时前
WPF应用最小化到系统托盘
wpf
qiangshang99012617 小时前
WPF+MVVM入门学习
学习·wpf
DASXSDW17 小时前
Abp vNext-事件总线使用实现及解析
ui·wpf
纸照片17 小时前
【邪修玩法】如何在WPF中开放 RESTful API 服务
后端·wpf·restful
啊丢_20 小时前
WPF基本布局容器与控件
wpf
c#上位机1 天前
wpf之RelativeSource用法总结
c#·wpf
玖笙&4 天前
✨WPF编程基础【2.1】布局原则
c++·wpf·visual studio
玖笙&4 天前
✨WPF编程基础【2.2】:布局面板实战
c++·wpf·visual studio
SEO-狼术4 天前
.NET WPF 数据编辑器集合提供列表框控件
.net·wpf