在Silverlight自定义控件中添加依赖属性

前言

  最近项目中在使用Silverlight做开发,需要用到自定义属性,便有了此文。(纯属学习使用阶段)

准备工作

    场景:要求文本框中输入值都是大写字母;

    实现方式:通过自定义属性形式实现;

    前期工作: 新建工程"CustomControlDemo_SL",并添加类:MyTextBox,使其继承自TextBox.

自定义依赖属性

     先看一下如何自动生成依赖属性的模板:在类MyTextBox中:输入"propd” –> tab键两次,便可生成定义依赖属性的模板,如下图:

输入"propdp":

image

tab键后生成的结构如下图:

image

有时候我们需要通过简单的属性设置便能实现文本框的格式控制,我们这里通过定义MaskType属性来实现输入控制(比如:只能输入大写字母)。实现自定义MaskType属性步骤如下:

1.先定义一个枚举MaskType:

 1     /// <summary>
2 /// 掩码类型
3 /// </summary>
4 public enum MaskType
5 {
6 /// <summary>
7 /// 默认,字母或整数
8 /// </summary>
9 Default,
10
11 /// <summary>
12 /// 大写字母
13 /// </summary>
14 Upper,
15
16 /// <summary>
17 /// 整数
18 /// </summary>
19 Integer,
20
21 /// <summary>
22 ///
23 /// </summary>
24 None
25 }

 
2.定义MaskType属性
 1         /// <summary>
2 /// 掩码类型
3 /// </summary>
4 public MaskType MaskType
5 {
6 get { return (MaskType)GetValue(MaskTypeProperty); }
7 set { SetValue(MaskTypeProperty, value); }
8 }
9
10 // Using a DependencyProperty as the backing store for MaskType. This enables animation, styling, binding, etc...
11 public static readonly DependencyProperty MaskTypeProperty =
12 DependencyProperty.Register("MaskType", typeof(MaskType), typeof(MyTextBox), new PropertyMetadata(MaskType.Default));


 

3.在文本框输入时对输入文本进行控制,我们可以通过重写OnTextInput(TextCompositionEventArgs e)方法实现。代码如下:

 1         /// <summary>
2 /// 重写基类OnTextInput方法
3 /// </summary>
4 /// <param name="e"></param>
5 protected override void OnTextInput(TextCompositionEventArgs e)
6 {
7 string input = e.Text;
8 switch (this.MaskType)
9 {
10 case MaskType.None:
11 break;
12 case MaskType.Integer:
13 e.Handled = !Regex.IsMatch(input, @"^[0-9]\d*$");
14 break;
15 case MaskType.Upper:
16 e.Handled = !Regex.IsMatch(input, @"^[A-Z]+$");
17 break;
18 default:
19 e.Handled = !Regex.IsMatch(input, @"^[A-Za-z0-9]+$");
20 break;
21 }
22 base.OnTextInput(e);
23 }


通过上面三步,一个简单具有自定义属性MaskType的MyTextBox控件就定义好了。下面我们就可以使用该控件了。

在CustomControlDemo_SL的Mainpage里使用刚才我们定义的控件,代码如下:

xaml代码:

<UserControl x:Class="CustomControlDemo_SL.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:demo="clr-namespace:CustomControlDemo_SL"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">

<Grid x:Name="LayoutRoot" Background="White">
<demo:MyTextBox MaskType="Upper" Height="20" Width="100"></demo:MyTextBox>
</Grid>
</UserControl>

这里我们设置的MaskType为Upper,标识仅能输入大写字母。

cs文件:默认,无需改动。

F5运行可以发现文本框只能输入大写字母了,达到我们预先的要求了。

注:上述的自定义属性还可以完善一点,我们可以在MyTextBox中一个Mask依赖属性,来指定MaskType的掩码。比如:当MaskType为Integer时,指定Mask为"DD”标识只能输入正整数,"dd"标识只能输入负整数。

作者:ps_zw
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
原文地址:https://www.cnblogs.com/pszw/p/2312269.html