这是依赖属性的样例:
public class TextBoxEx : TextBox
{
static TextBoxEx()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(TextBoxEx), new FrameworkPropertyMetadata(typeof(TextBoxEx)));
}
public TextBoxEx()
{
this.Loaded += loaded;
this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Paste, null, commandBinding_CanExecute));
this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Copy, null, commandBindingCopy_CanExecute));
}
public static DependencyProperty BorderCornerRadiusProperty =
DependencyProperty.Register("BorderCornerRadius", typeof(CornerRadius), typeof(TextBoxEx));
public static readonly DependencyProperty RegexProperty =
DependencyProperty.Register("Regex", typeof(string), typeof(TextBoxEx), new PropertyMetadata("[^0-9]+"));
public static readonly DependencyProperty IsRegexOnlyProperty =
DependencyProperty.Register("IsRegexOnly", typeof(bool), typeof(TextBoxEx), new PropertyMetadata(false));
public static readonly DependencyProperty IsPasteProperty =
DependencyProperty.Register("IsPaste", typeof(bool), typeof(TextBoxEx), new PropertyMetadata(true));
public static readonly DependencyProperty IsSpaceProperty =
DependencyProperty.Register("IsSpace", typeof(bool), typeof(TextBoxEx), new PropertyMetadata(true));
/// <summary>
/// 边框角度
/// </summary>
public CornerRadius BorderCornerRadius
{
get { return (CornerRadius)GetValue(BorderCornerRadiusProperty); }
set { SetValue(BorderCornerRadiusProperty, value); }
}
/// <summary>
/// 获取或设置正则表达式
/// </summary>
public string Regex
{
get { return (string)GetValue(RegexProperty); }
set { SetValue(RegexProperty, value); }
}
/// <summary>
/// 获取或设置是否只接受正则表达式匹配的内容
/// </summary>
public bool IsRegexOnly
{
get { return (bool)GetValue(IsRegexOnlyProperty); }
set { SetValue(IsRegexOnlyProperty, value); }
}
/// <summary>
/// 获取或设置是否禁用粘贴功能
/// </summary>
public bool IsPaste
{
get { return (bool)GetValue(IsPasteProperty); }
set { SetValue(IsPasteProperty, value); }
}
/// <summary>
/// 获取或设置是否禁用空格功能
/// </summary>
public bool IsSpace
{
get { return (bool)GetValue(IsSpaceProperty); }
set { SetValue(IsSpaceProperty, value); }
}
/// <summary>
/// 黏贴方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void commandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (IsPaste && IsRegexOnly)
{
string str = Clipboard.GetText();
System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(Regex);
e.Handled = re.IsMatch(str);
}
else
{
e.Handled = !IsPaste;
}
}
/// <summary>
/// 复制方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void commandBindingCopy_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.Handled = false;
}
/// <summary>
/// 按键方法
/// </summary>
/// <param name="e"></param>
protected override void OnPreviewKeyDown