【问题标题】:WPF datagrid refreshes on it's own when it's not supposed toWPF datagrid 在不应该刷新时自行刷新
【发布时间】:2011-05-21 20:30:51
【问题描述】:

我觉得我在这里遗漏了一些东西,但是我有这个数据网格,当数据源发生变化时,它会自动重绘它,而没有任何逻辑理由这样做。

我将数据网格绑定到实现 INotifyPropertyChanged 的​​ DataView 属性,并且我想在调用 Refresh() 之前触发该事件时做一些其他事情。

所以这里是数据源。

public class MainScreenDataView : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }

    DataView _dataview;

    public DataView GetDataView
    {
        get { return _dataview; }
        set
        {
            _dataview = value;
            OnPropertyChanged("GetDataView");
        }
    }
    public MainScreenDataView()
    {
    }
}

还有绑定(我在窗口的构造函数中调用这个)

    public void MakeData()
    {
        MiddleMan midman = MiddleMan.Instance; 
        midman.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(midman_PropertyChanged); //unrelated event for error messages
        midman.InstantiateAll();


        Binding bind = new Binding();
        bind.Source = midman.GetDict["contact"].GetDataView; //GetDict is a dictionary that holds instances of MainScreenDataView
        bind.UpdateSourceTrigger = UpdateSourceTrigger.Explicit;
        DG_Contacts.SetBinding(BetterDataGrid.ItemsSourceProperty, bind);
    }

使用来自数据库的数据更新 DataView 的类可以访问与窗口相同的 MainScreenDataView 实例。该实例以单例形式保存在字典中。

现在我看不出数据网格为什么会自行刷新,我什至尝试从 MainScreenDataview 中删除 INotifyPropertyChanged 内容,但它保持相同的行为。

猜猜我在这里遗漏了一些东西。某处需要覆盖的默认行为或其他什么?

【问题讨论】:

    标签: c# wpf data-binding datagrid dataview


    【解决方案1】:

    你已经交换了目标和源。我自己做的。 UpdateSourceTrigger.Explicit 设置影响绑定如何更新 source,它是 MainScreenDataView.GetDataView 属性而不是 DataGrid.ItemSourceDataGrid.ItemSource目标

    MainScreenDataView 中删除INotifyPropertyChanged 对单例没有影响,因为实例不会改变,只会改变实例内的值。换句话说,GetDataView 是一个“一劳永逸”的属性。

    只要绑定有效,就无法阻止对集合所做的更改被绑定系统传播,除非您禁止触发或阻止 DataView.CollectionChanged 事件,以便绑定子系统根本不会运行。

    如果您真的想要这样做,您可以断开绑定并在准备好时重新设置,或者创建一个全新的DataView 并在准备好时覆盖绑定。

    【讨论】:

    • 我明白了……好吧还是有点困惑。猜猜我不需要使用 Binding 对象,我也可以执行“DataGrid.ItemsSource = pathtodataview;”,但即便如此它也会自动刷新。 ------------- 我想在“MainScreenDataView”的“propertychanged”事件中执行刷新逻辑,因此取消绑定和重新绑定不会真正起作用,因为在事件触发之前网格开始重绘。
    • 我不清楚的部分是为什么要延迟刷新?
    • 这是为了这个令人尴尬的小东西。我只是想在刷新网格后保留选择,以使重新加载看起来更加无缝。
    • 再想一想,我可能可以通过将选定的索引保存在“selectionchanged”上并将它们重新应用到我的“propertychanged”事件中,因为它会在网格更新后立即触发
    猜你喜欢
    • 2012-12-09
    • 1970-01-01
    • 2014-07-27
    • 2011-03-26
    • 2013-11-06
    • 2010-12-19
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多