2009-07-07 55 views
0

我有一个WinForms窗体,其中包含一个ElementHost控件(其中包含一个WPF UserControl)和一个保存按钮。在ElementHost控件WPF验证

在WPF UserControl中,我有一个文本框,其中包含一些验证。像这样...

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

这一切工作正常。然而,我想要做的是在窗体处于无效状态时禁用“保存”按钮。

任何帮助将不胜感激。

回答

0

嗯,我终于找出了解决我的问题。

在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布尔的事件。然后,我可以在我的表单上连接这个事件,告诉它该控件是否有效。

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

1

我想这应该可以帮助您:

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

那么你也许可以告知的MainForm关于与该用户控件注册事件的变化。