一、问题与目的:
学习Silverlight已经有一段时间了。一直没时间写一篇学习笔记(如有错误,望同仁们指出,其实也很简单,就当做个笔记了)。
关于Silverlight的DatePicker控件,原来的DatePicker控件,不可控制是否能手动输入。如果允许用户手动输入,则会出现错误输入日期格式的情况,但是,DatePicker未提供一个属性来获取DatePicker错误输入的内容,不能做到正确提示,也不可代码清空文本内容,当然,错误输入可引发DateValidationError事件,但是只有事件CalendarClosed和CalendarOpened引发此事件验证,很不方便。因此重写了DatePicker!
二、解决办法
在控件中添加IsReadOnly属性,控制是否手动输入,再添加InputText属性,获取错误输入的文本内容。可同步控件本身的Text属性。这样,既可以控制用户手动输入,也可以获取用户错误输入内容,方便代码人员提示!
三、代码
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Controls.Data;
public class DatePickerEx : DatePicker
{
#region 私有字段
TextBox CurrentTextBox;
public static readonly DependencyProperty IsReadOnlyProperty = DependencyProperty.Register("IsReadOnly",typeof(bool),typeof(DatePickerEx),new PropertyMetadata(false));
public static readonly DependencyProperty InputTextProperty = DependencyProperty.Register("InputText",typeof(String),new PropertyMetadata("",InputTextChanged));
#endregion
#region 属性
/// <summary>
/// 得到手动输入的值
/// </summary>
public string InputText
{
get { return (string)GetValue(InputTextProperty); }
set { SetValue(InputTextProperty,value); }
}
/// <summary>
/// 启用和关闭手动输入
/// </summary>
public bool IsReadOnly
{
get { return (bool)GetValue(IsReadOnlyProperty); }
set { SetValue(IsReadOnlyProperty,value); }
}
#endregion
#region 重写方法及事件
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
this.CurrentTextBox = GetTemplateChild("TextBox") as TextBox;
this.CalendarClosed += new RoutedEventHandler(DatePickerEx_CalendarClosed);
}
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
if (!this.IsReadOnly)
this.InputText = this.CurrentTextBox.Text;
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (this.IsReadOnly)
e.Handled = this.IsReadOnly;
}
#endregion
#region 自定义事件
public virtual void DatePickerEx_CalendarClosed(object sender,RoutedEventArgs e)
{
this.InputText = this.Text;
}
protected static void InputTextChanged(DependencyObject d,DependencyPropertyChangedEventArgs e)
{
DatePickerEx sender = d as DatePickerEx;
sender.CurrentTextBox.Text = e.NewValue.ToString();
}
#endregion
}
使用方式在XAML页 添加(xmlns:ControlsEx="clr-namespace:FXD.CommonLib.Controls;assembly=FXD.CommonLib") 引用,当然,此组件引用根据实际情况而改变; 使用控件时; <controlsEx:DatePickerEx IsReadOnly="True" Height="23" Margin="5,0" InputText="{Binding SearchDate,Mode=TwoWay}" Width="120" />
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。