开发者

Silverlight Required TextBox Attached Property

I have a need to create an attached property for a TextBox, that enforces a rule that content is required.

NOTE: Unfortunately I am not able to use data annotations, or SL4 validation frameworks.

The textboxes are displayed within the context of a View. The View is reused in many places. When tabbing / clicking between TextBoxes within the view I want a popup message to notify the user if they have left a 'Required' TextBox empty.

Now, I have this working via the LostFocus event:

开发者_如何学JAVA
    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();
            }
        };
    }

But this is getting triggered, obvioulsy, on every lost focus, and there are certain situations, for example closing the view, that i don't want the validation to execute.

So, does anyone have any good suggestions (or examples) on a way to get a Required Text Box service working within a definable scope of actions? Or perhaps some clever alternatives to LostFocus that I could use?

Thanks, Mark

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜