如何捕获数据绑定控件中的用户更改?
我的应用程序充满了绑定到我的类的各种控件数据。我想询问用户“您正在关闭应用程序并进行了一些更改。您想保存更改吗?”。为此,我需要识别用户进行了任何更改。
如何捕获用户在数据绑定控件中所做的更改? textBoxXXX_TextChanged 是执行此操作的唯一方法吗?
预先感谢您的所有回答。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这取决于数据源;例如,DataTable 和 DataSet 源包含
GetChanges()
方法,使您可以轻松查看是否已添加/删除/修改行。其他数据源将有自己的实现(如果有)。如果没有实施,则由您决定如何检查这些更改。无论如何,这是您应该在数据级别而不是 UI 上执行的操作(通过监视“更改”事件)。观看事件的规模无法超出几个控制范围,并且维护可能会很困难。
更新:不知道为什么我没有想到它,但第二个选择是向您的 UI 对象添加
BindingSource
并将其用作数据绑定代理(您的 UI控制数据绑定到BindingSource
并且BindingSource
绑定到真实的数据源)。它提供了一种比处理所有单独的“Control_Changed”事件以及需要重新设计其他层(特别是如果它们不是自定义数据类型)更好的方法。It depends on the datasource; for example DataTable and DataSet sources contain the
GetChanges()
methods which allow you to easily see if rows have been added/removed/modified. Other data sources will have their own implementations, if any. If there is no implementation then it's up to you to determine how to check for those changes.In any event this is something you should do at the data-level, not the UI (by watching for "changed" events). Watching events doesn't scale beyond a couple controls and maintenance can be iffy.
Update: Not sure why I didn't think of it, but a second option is to add a
BindingSource
to your UI object and use it as a databinding proxy (your UI controls databind to theBindingSource
and theBindingSource
binds to the real datasource). It provides a better approach than handling all your individual "Control_Changed" events, and requiring rework of your other layers (esp. if they aren't custom data-types).您需要为此提供自定义逻辑,实际上并没有一种自动方法来执行此操作。在我看来,有几个选项:
You need to provide custom logic for that, there's not really an automatic way of doing this. As I see it there are several options:
正如我们所讨论的,有很多方法可以做到这一点,具体取决于您想要获得的粒度。
使用客户端 JavaScript 的一种相对简单的方法是执行如下操作:
onchange
事件。您可以使用 javascript/DOM 在页面加载时动态执行此操作。pageHasChanged = true;
beforeonunload
事件(当用户尝试离开时发生)页面)并检查pageHasChanged
变量以查看是否进行了任何更改。如果进行了更改,您可以提醒用户。这不会为您提供更改内容的详细信息,但很容易修改以跟踪哪些表单元素发生了更改。
As been discussed, there are many ways to do this depending on how granular you want to get.
A relatively easy way using client side javascript would be to do something like the following:
onchange
events of the form elements. You could do this dynamically on page load using javascript/DOM.pageHasChanged = true;
beforeonunload
event (occurs when the user tries to navigate away from the page) and check thepageHasChanged
variable to see if any changes were made. If changes were made you could alert the user.This doesn't give you the detail of what changed, but would be fairly easy to modify to track which form elements changed.