如何在数据加载时阻止计算绑定文本框上的 UpdateSource?
当用户在 3 个文本框中输入数字时,我会在第 4 个文本框中计算平均值。从前 3 个文本框的 TextChanged 事件中调用CalculateAverage 方法。所有文本框均已绑定。 (注意:我知道计算值不应存储在数据库中,但我无法更改这一点。)我使用的是 WPF 4 和 Entity Framework 4。
我的问题是平均文本框始终具有 EntityState.Modified 。这是因为加载数据或导航记录会导致 TextChanged 事件调用CalculateAverage。即使用户没有进行更改并且 CurrentValue(平均值)与 OriginalValue 匹配,绑定机制现在也会认为该记录是“脏”的。
我想知道是否有比我实施的解决方案更干净的解决方案。我的解决方法是在数据加载和记录导航期间设置一个标志。这意味着我必须添加 OnRecordChanging 事件来设置 _changingRecords 标志,并添加 OnRecordChanged 事件来取消设置。在CalculateAverage 的开头,我有: if (_loadingData || _changingRecords) return;
来退出CalculateAverage 并防止更新平均字段。
有没有更干净的方法来避免这个问题?
As users enter numbers into 3 text boxes I calculate the average in a 4th text box. The CalculateAverage method is called from the TextChanged event of the first 3 text boxes. All text boxes are bound. (Note: I know calculated values should not be stored in a database, but I'm not able to change this.) I'm using WPF 4 and Entity Framework 4.
My problem is that the average text box always has EntityState.Modified. This is because loading data or navigating records causes the TextChanged event to call CalculateAverage. Even though the user has not made changes and the CurrentValue (of average) matches the OriginalValue the binding mechanism now considers this record to be "dirty".
I'm wondering if there is a cleaner solution than the one I've implemented. My fix is to set a flag during data load and during record navigation. This means I had to add an OnRecordChanging event to set the _changingRecords flag and an OnRecordChanged event to un-set it. At the beginning of CalculateAverage I have: if (_loadingData || _changingRecords) return;
to bail out of CalculateAverage and prevent an update to the average field.
Is there a cleaner approach to avoiding this issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这会起作用,我们实际上在一个项目上做了同样的事情,以避免控件之间的“事件风暴”。
您应该注意的一件事是错误情况,这样您就不会陷入“正在加载”状态,从而导致更新停止工作。
That will work, we have actually done the same thing on a project, to avoid "event storms" between controls.
One thing you should watch out for is error conditions, so that you do not get stuck in a "loading" state so that the updates stop working.