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

}

}

}

相关推荐
weixin_4471035821 分钟前
Wpf布局之StackPanel!
wpf
小老鼠爱大米22 分钟前
[C#] WPF - 资源URI
c#·wpf·uri
三千道应用题8 小时前
WPF学习笔记(13)列表框控件ListBox与数据模板
wpf
甄天9 天前
WPF中MVVM和MVVMLight模式
c#·wpf·visual studio
CoderIsArt12 天前
C# WPF常用调试工具汇总
开发语言·c#·wpf
凉、介12 天前
SylixOS 下的消息队列
linux·wpf·sylixos
Magnum Lehar12 天前
wpf3d游戏引擎ProjectLayoutView实现
游戏引擎·wpf
摆烂的少年12 天前
WPF中自定义DataGrid表格后,修改选中行的字体颜色或背景图
wpf
CoderIsArt12 天前
WPF调试三种工具介绍:Live Visual Tree、Live Property Explorer与Snoop
wpf
甄天12 天前
WPF Style样式 全局样式资源字典
c#·wpf