【问题标题】:WPF Update UI after Revert Changes From LINQ to SQL将更改从 LINQ 还原为 SQL 后 WPF 更新 UI
【发布时间】:2019-01-18 17:34:27
【问题描述】:

我阅读了这个问题,但很遗憾在还原更改后没有找到任何更新 ui 的解决方案。

How can I reject all changes in a Linq to SQL's DataContext?

我所有的属性都派生自 INotifyPropertyChanged。

var changeSet = dataContext.GetChangeSet();
if (changeSet != null)
{
    var updates = changeSet.Updates.ToArray();
    dataContext.Refresh(RefreshMode.OverwriteCurrentValues, changeSet.Updates);

    foreach (var o in updates)
    {
        INotifyPropertyChanged entity = (INotifyPropertyChanged)o;
        // What i have to do to force them trigger PropertyChanged event ???
    }
}

【问题讨论】:

  • 这完全取决于您的设计。通常,您需要检查每个 UI 对象以查看它们是否需要更新。
  • @Bijan 感谢您的回复,但我正在寻找另一种解决方案。问题的根源在于 dataContext.Refresh() 方法没有触发 onPropertyChanged 事件。您对此有什么建议吗?
  • 我不明白你的问题。为什么要在事件上触发刷新?断点命中刷新吗?您是否在刷新之前保存了上下文?
  • @Bijan 让我再解释一下。我有一个带有一些用户控件的 WPF 应用程序。所有 UI 元素都绑定到数据上下文,对有界控件的任何更改都会自动反映到数据上下文的 ChangeSet。如果我在 UI 中更改 TextBox 内容,将触发 onPropertyChanged 事件。但是如果我调用 DataContext.Refresh(RefreshMode.OverwriteCurrentValues, changeSet.Updates);注意发生。所以我正在寻找一种手动执行相同行为的方法。
  • IMO 如果你需要这个设计是有缺陷的。您应该使用视图模型,并且只在用户集中注意力后修改实体对象。如果他们取消编辑操作,您只需丢弃更改的视图模型对象,并且没有实体对象看到更改。

标签: c# wpf linq datacontext inotifypropertychanged


【解决方案1】:

首先我向我的所有 Linq2SQL 类添加一个方法:

public partial class Setting
{
    public void SendPropertyChangedFromOutside(string propName)
    {
        SendPropertyChanged(propName);
    }
}

public partial class User
{
    public void SendPropertyChangedFromOutside(string propName)
    {
        SendPropertyChanged(propName);
    }
}

然后调用UndoDBChanges方法:

public static void UndoDBChanges(System.Data.Linq.DataContext dataContext) {
var changeSet = dataContext.GetChangeSet();
if (changeSet != null)
{
    var updates = changeSet.Updates.ToArray();
    dataContext.Refresh(RefreshMode.OverwriteCurrentValues, changeSet.Updates);

    foreach (var o in updates)
    {
        try
        {
            Type t = o.GetType();
            dynamic obj = Convert.ChangeType(o, t);

            foreach (System.Reflection.PropertyInfo prop in t.GetProperties())
            {
                obj.SendPropertyChangedFromOutside(prop.Name);
            }
        }
        catch
        { }
    }
}}

【讨论】:

    猜你喜欢
    • 2015-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-31
    • 2015-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多