views:

445

answers:

2

I've got a WinForms form that contains an ElementHost control (which contains a WPF UserControl) and a Save button.

In the WPF UserControl I've got a text box with some validation on it. Something like this...

<TextBox Name="txtSomething" ToolTip="{Binding ElementName=txtSomething, Path=(Validation.Errors).[0].ErrorContent}">
    <Binding NotifyOnValidationError="True" Path="Something">
        <Binding.ValidationRules>
            <commonWPF:DecimalRangeRule Max="1" Min="0" />
        </Binding.ValidationRules>
    </Binding>
</TextBox>

This all works fine. What I want to do however, is disable the Save button while the form is in an invalid state.

Any help would be greatly appreciated.

A: 

Well, I've finally worked out a solution to my problem.

In the WPF control I added this to the Loaded event.

Validation.AddErrorHandler(this.txtSomething, ValidateControl);

Where ValidateControl above, is defined as this:

private void ValidateControl(object sender, ValidationErrorEventArgs args)
{
    if (args.Action == ValidationErrorEventAction.Added)
       OnValidated(false);
    else
       OnValidated(true);
}

Finally I added an event called Validated which contains an IsValid boolean in its event args. I was then able to hook up this event on my form to tell it that the control is valid or not.

If there is a better way I'd be interested to learn.

Jon Mitchell
A: 

I think this should help you:

<UserControl Validation.Error="Validation_OnError >
<UserControl.CommandBindings>   
    <CommandBinding Command="ApplicationCommands.Save" CanExecute="OnCanExecute" Executed="OnExecute"/> 
</UserControl.CommandBindings> 
...
<Button Command="ApplicationCommands.Save" />
...
</UserControl>

/* put this in usercontrol's code behind */
int _errorCount = 0;
private void Validation_OnError(object sender, ValidationErrorEventArgs e)
{
    switch (e.Action)
    {
        case ValidationErrorEventAction.Added:
            { _errorCount++; break; }
        case ValidationErrorEventAction.Removed:
            { _errorCount--; break; }
    }
}

private void OnCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = _errorCount == 0;
}

Then you could perhaps inform the mainform about a change with an event registered on the usercontrol.

PaN1C_Showt1Me