【问题标题】:How can I force a bound datagrid to refresh the contents?如何强制绑定数据网格刷新内容?
【发布时间】:2013-09-13 15:55:57
【问题描述】:

我对 Silverlight 开发比较陌生,遇到过以下场景:

我有一个绑定到域数据源的 DataGrid。有时会通过外部实体对数据进行更新。 DataSource 随后通过 Clear() 和 Load() 重新加载。

问题在于,完成此操作后,网格中的数据不会刷新,除非更改的字段之一是键的一部分。否则,似乎会显示实体先前数据的缓存版本。

我可以通过向要返回的数据集添加时间戳并将其作为密钥的一部分来解决此问题,但在我看来,这是一个不必要的 hack。刷新数据的正确方法是什么?

【问题讨论】:

    标签: c# silverlight-4.0


    【解决方案1】:

    我希望你遵循 MVVm 结构。

    将列表更改为可观察的集合,我希望您从 xaml 绑定它

    这是可能对您有用的代码。

        public partial class MainPage : UserControl, INotifyPropertyChanged
    {
        private ObservableCollection<Customer> _MyList = 
            new ObservableCollection<Customer>();
        public ObservableCollection<Customer> MyList
        {
            get { return _MyList; }  
        } 
    
        public MainPage()
        {                      
            InitializeComponent();
    
            this.DataContext = this;
    
            MyList.Add(new Customer{ _nome = "Josimari", _idade = "29"});
            MyList.Add(new Customer{_nome = "Wesley", _idade = "26"});
            MyList.Add(new Customer{_nome = "Renato",_idade = "31"});
    
            OnPropertyChanged("MyList"); // This only works if you use bindings.
        }
    
        private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            MyList.Add(new Customer{_nome = "Maiara",_idade = "18"});   
    
            OnPropertyChanged("MyList"); // This only works if you use bindings.
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged( string propertyName )
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        } 
    }
    

    如果它不起作用,请告诉我。

    【讨论】:

      猜你喜欢
      • 2011-08-06
      • 2016-10-20
      • 1970-01-01
      • 2010-11-24
      • 1970-01-01
      • 1970-01-01
      • 2014-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多