如何为空文本框触发WPF验证规则? [英] How do I get a WPF validation rule to fire for an empty text box?
问题描述
我无法获得WPF ValidationRule
来检测空 TextBox
。
我的缩减代码如下:
I am unable to get a WPF ValidationRule
to detect an empty TextBox
.
My cut-down code is as follows:
public class NonEmptyStringValidator : ValidationRule
{
public override ValidationResult Validate( object value, CultureInfo cultureInfo )
{
ValidationResult validationResult = new ValidationResult( false, "Value cannot be empty." );
if( value != null )
{
string valueAsString = value as string;
if( valueAsString.Length > 0 )
validationResult = ValidationResult.ValidResult;
}
return validationResult;
}
}
我的缩减XAML如下:
My cut-down XAML is as follows:
<TextBox
<TextBox.Text>
<Binding Path="SelectedUser.Username" UpdateSourceTrigger="LostFocus">
<Binding.ValidationRules>
<u:NonEmptyStringValidator/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
一个断点放在 Validate()
函数显示t在 TextBox
中存在某些内容之前,代码不会运行。有没有办法让它发挥作用来检测空字符串?
我尝试过:
我为 UpdateSourceTrigger
尝试了各种值。
我也尝试过为 TextBox
挂钩 LostFocus
事件并编写代码来手动处理。这变得非常混乱,因为我需要做的一件事就是将注意力集中在 TextBox
上,直到它有内容,然后调用 Focus()
似乎导致 LostFocus
事件再次触发,这是我不理解的事情。
A breakpoint placed inside the Validate()
function reveals that the code is not run until there is something in the TextBox
. Is there a way to get it to work to detect an empty string?
What I have tried:
I have tried various values for UpdateSourceTrigger
.
I have also tried hooking into the LostFocus
event for the TextBox
and writing code to handle this manually. This gets very messy because one thing I need to do is keep focus on the TextBox
until is has something in it, and calling Focus()
seems to cause the LostFocus
event to fire again, which is something else I don't understand.
推荐答案
快速 Google搜索 [ ^ ]
发现这些:
* WPF:强制附加到要执行的对象的所有验证规则 - Prim ordial Code [ ^ ]
* 强制验证WPF中的绑定控件 - Stack Overflow [ ^ ]
A quick Google Search[^]
Found these:
* WPF: Force all the validation rules attached to an object to be executed - Primordial Code[^]
* Force validation on bound controls in WPF - Stack Overflow[^]
这篇关于如何为空文本框触发WPF验证规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!