ElementHost控件中的WPF验证

ElementHost控件中的WPF验证,wpf,validation,elementhost,Wpf,Validation,Elementhost,我有一个WinForms表单,它包含一个ElementHost控件(其中包含一个WPF UserControl)和一个Save按钮 在WPF用户控件中,我有一个文本框,上面有一些验证。像这样的 <TextBox Name="txtSomething" ToolTip="{Binding ElementName=txtSomething, Path=(Validation.Errors).[0].ErrorContent}"> <Binding NotifyOnValid

我有一个WinForms表单,它包含一个ElementHost控件(其中包含一个WPF UserControl)和一个Save按钮

在WPF用户控件中,我有一个文本框,上面有一些验证。像这样的

<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>

这一切都很好。但是,我想做的是在表单处于无效状态时禁用保存按钮


任何帮助都将不胜感激。

嗯,我终于找到了解决问题的办法

在WPF控件中,我将其添加到
Loaded
事件中

Validation.AddErrorHandler(this.txtSomething, ValidateControl);
其中,上面的
ValidateControl
定义如下:

private void ValidateControl(object sender, ValidationErrorEventArgs args)
{
    if (args.Action == ValidationErrorEventAction.Added)
       OnValidated(false);
    else
       OnValidated(true);
}
最后,我添加了一个名为
Validated
的事件,该事件在其事件参数中包含一个
IsValid
布尔值。然后,我能够在我的表单上连接这个事件,告诉它控件是否有效


如果有更好的学习方法,我会感兴趣的。

我认为这应该对您有所帮助:

<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;
}