Silverlight必需TextBox附加属性

时间:2010-05-28 11:06:06

标签: silverlight textbox attached-properties

我需要为TextBox创建附加属性,该属性强制执行需要内容的规则。

注意:很遗憾,我无法使用数据注释或SL4验证框架。

文本框显示在视图的上下文中。 View在很多地方都可以重复使用。当在视图中的TextBoxes之间进行选项卡/单击时,我希望弹出消息通知用户是否已将“Required”TextBox留空。

现在,我通过 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 的一些聪明的替代品?

谢谢, 标记

0 个答案:

没有答案