如何为空文本框触发WPF验证规则?

编程入门 行业动态 更新时间:2024-10-26 00:20:54
本文介绍了如何为空文本框触发WPF验证规则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我无法获得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验证规则?

本文发布于:2023-11-23 03:32:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619927.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本框   规则   WPF

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!