验证.对于WPF ValidationRule, GetHasError总是返回true
本文关键字:返回 true GetHasError 对于 WPF ValidationRule 验证 | 更新日期: 2023-09-27 18:04:52
我看到了一个很好的解决方案,用于测试contrôls组的验证:
In my windows .xaml.cs:
private bool IsValid(DependencyObject obj)
{
// The dependency object is valid if it has no errors,
//and all of its children (that are dependency objects) are error-free.
return !Validation.GetHasError(obj) &&
LogicalTreeHelper.GetChildren(obj)
.OfType<DependencyObject>()
.All(child => IsValid(child));
}
我的问题是,在我的情况下,即使我有错误,isValid总是返回true。我想是因为一个错误,但是…在哪里?
这是我的Windows。XAML:
<Window.Resources>
<CommandBinding x:Key="binding" Command="Save" Executed="Save_Executed" CanExecute="Save_CanExecute" />
</Window.Resources>
<TextBox Name="TextBox_TypeEvenement" Grid.Column="1" VerticalAlignment="Center" Height="20">
<TextBox.Text>
<Binding Path="strEvtType">
<Binding.ValidationRules>
<ExceptionValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
<Button Template="{StaticResource BoutonRessourcesTpl}" Command="Save">
<Button.CommandBindings>
<StaticResource ResourceKey="binding"></StaticResource>
</Button.CommandBindings>
<Image Source= "Toolbar_Valider.png" Height="16"/>
</Button>
这是我的class。cs c#:
private string m_strEvtType;
public string strEvtType
{
get { return m_strEvtType; }
set {
m_strEvtType = value;
if (m_objEvtCode.ReadEvtTypebyType(m_strEvtType) != 0)
{
throw new ApplicationException(m_strEvtType.Trim() + " est innexistant !");
}
FirePropertyChangedEvent("strEvtType");
FirePropertyChangedEvent("m_objEvtCode.strDes");
}
}
你知道为什么isValid总是返回true吗?
谢谢你:)
敬礼:)
我认为问题是All
在你的Linq
中的使用
如果源序列的每个元素都通过,All将返回true在指定谓词或序列为空中进行测试;否则,假的。
所以如果DependencyObject
上没有子DependencyObjects
All
将返回true
尝试使用其他Linq方法,如Any
来检查您的IsValid
条件
return !Validation.GetHasError(obj) &&
!LogicalTreeHelper.GetChildren(obj)
.OfType<DependencyObject>()
.Any(child => !IsValid(child));