我需要为 TextBox 创建一个附加属性,该属性强制执行需要内容的规则。
注意:不幸的是,我无法使用数据注释或 SL4 验证框架。
文本框显示在视图的上下文中。视图在许多地方被重用。在视图中的文本框之间切换/单击时,我希望弹出消息通知用户是否将“必需”文本框留空。
现在,我通过LostFocus事件进行了这项工作:
public static readonly DependencyProperty RequiredProperty =
DependencyProperty.RegisterAttached("Required", typeof(bool), typeof(TextBoxRequiredService),
new PropertyMetadata(OnRequiredChanged));
public static bool GetRequired(DependencyObject d)
{
return (bool)d.GetValue(RequiredProperty);
}
public static void SetRequired(DependencyObject d, bool value)
{
d.SetValue(RequiredProperty, value);
}
private static void OnRequiredChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TextBox textBox = d as TextBox;
textBox.LostFocus += (s, args) => {
if (textBox.Text.Length == 0) {
MessageBox.Show("Required Field!");
textBox.Focus();
}
};
}
但这显然会在每个失去焦点时触发,并且在某些情况下,例如关闭视图,我不希望执行验证。
那么,对于在可定义的操作范围内获得所需文本框服务的方法,是否有人有任何好的建议(或示例)?或者也许我可以使用一些聪明的替代LostFocus的方法?
谢谢,马克