2009-07-07 80 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關於與該用戶控件註冊事件的變化。