C# 取消 WPF 文本框更改事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/335129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 23:40:46  来源:igfitidea点击:

Cancelling a WPF TextBox Changed Event

c#.netwpftextbox

提问by 1kevgriff

I'm in the process of learning WPF coming from WinForms development.

我正在学习来自 WinForms 开发的 WPF。

I have a TextChanged event assigned to one of my TextBox's in my WPF application. If the user enters invalid data, I want to be able to revert to the previous text value.

我有一个 TextChanged 事件分配给我的 WPF 应用程序中的 TextBox 之一。如果用户输入无效数据,我希望能够恢复到以前的文本值。

In the old forms day, I would replace NewValue with OldValue, but it seems WPF doesn't work the same way.

在旧的表单日,我会用 OldValue 替换 NewValue,但似乎 WPF 的工作方式不同。

Any ideas on what I could do it achieve this? Am I just not thinking with WPF yet?

关于我可以做什么来实现这一目标的任何想法?我只是还没有考虑 WPF 吗?

Thanks.

谢谢。

采纳答案by Dennis

You can do this two ways:

您可以通过两种方式执行此操作:

  1. Listen to the PreviewTextInputevent and set e.Handled = trueto stop the TextChanged event.

  2. Use WPF validation. There is a great post by Paul Stovell on Codeprojectand a recent post on his blog.

  1. 侦听PreviewTextInput事件并设置e.Handled = true为停止 TextChanged 事件。

  2. 使用 WPF 验证。有一个伟大的职位由保罗Stovell在CodeProject最近的文章在他的博客

Those articles will get you started. one thing that got stuck with when I first did validation is that the validation rule only runs when the binding updates the source.

这些文章会让你开始。我第一次进行验证时遇到的一件事是验证规则仅在绑定更新源时运行。

回答by sindre j

I would use PreviewTextInput, most events in WPF have a Preview sibling. If you set the e.Handled = true it will stop the event from bubbelig/tunneling further.

我会使用 PreviewTextInput,WPF 中的大多数事件都有一个预览兄弟。如果您设置 e.Handled = true,它将进一步阻止事件的冒泡/隧道传输。

I'm not sure if you are aware of it but Preview events are said to be tunneling, ie. they start from the outermost container and is posted in every container until it reaches the control that has focus. The non-preview events are said to be bubbeling, ie. they start at the control with focus, and is posted to every parent control.

我不确定您是否知道它,但据说预览事件是隧道,即。它们从最外面的容器开始,并在每个容器中发布,直到到达具有焦点的控件。非预览事件被称为冒泡,即。它们从具有焦点的控件开始,然后发布到每个父控件。

If you set e.Handled = true on the outermost grid's PreviewTextChanged event, you cancel all other events including the TextChanged as well. First all Preview events get fired from the outermost to the control with focus, then all non-preview events get fired from the control with focus and out to the outermost parent control.

如果您在最外层网格的 PreviewTextChanged 事件上设置 e.Handled = true,您也会取消所有其他事件,包括 TextChanged。首先,所有预览事件都从最外层的有焦点的控件触发,然后所有非预览事件从有焦点的控件中触发,并输出到最外层的父控件。