views:

155

answers:

0

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:

    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