c# - IsDirty 对 EF 实体使用 INotifyPropertyChanged

标签 c# .net wpf entity-framework data-binding

给定一个使用 WPF 双向绑定(bind)到 EF 实体对象的标准记录编辑表单

IsDirty 处理如下

entity.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(ct_PropertyChanged);
DataContext = entity;

void entity_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
    IsDirty = true;
}

void SaveAndClose()
{
    if ( IsDirty ) { // doSave }
    Close();
}

一切都很好,除非用户只更改 fieldX 并点击保存(在这种情况下这是一个有效的模型!)

问题是在执行 Close() 之前不会调用 PropertyChanged(),因此不会保存记录

有什么方法可以强制使用“Binder”或任何其他替代方法?

最佳答案

我假设 UpdateSourceTriggerLostFocus,因此当控件 (filedX) 失去焦点时属性会更新。例如。用户单击将光标设置为另一个控件。

一种可能性是,将 UpdateSourceTrigger 设置为 PropertyChanged

另一种方法是强制当前获得焦点的元素更新源。

这是一个文本框的例子:

var focusedElement = Keyboard.FocusedElement;
if(focusedElement is TextBox)
{
    var bindingExpression = ((TextBox)focusedElement).GetBindingExpression(TextBox.TextProperty);
    if(bindingExpression != null)
    {
        bindingExpression.UpdateSource();
    }
}

关于c# - IsDirty 对 EF 实体使用 INotifyPropertyChanged,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9825110/

相关文章:

wpf - 在多个Y轴图中,wpf中的轴偏移问题

c# - 如何将 ItemsControl(在网格外)绑定(bind)到网格?

c# - 在 LINQ 中使用 Range() 打印偶数

c# - RelativeSource 绑定(bind)适用于 Style 但不适用于 ControlTemplate

c# - 如何将 Selectlist 转换为 Html.SelectListFor()

c# - 使用 LINQ 比较查询中的日期

c# - Windows 10 上的 ContextMenu 和 Popup WPF 控件对齐错误

.net - 生成自定义配置节的工具

c# - ASP.NET MVC 与 Winforms MVC

wpf - 在 Watermark 附加属性中绑定(bind) TextBox.Text 以将其本地化