【问题标题】:How to hook up Data Binding, Linq, DataGridView in the MVC way?如何以MVC的方式挂接Data Binding、Linq、DataGridView?
【发布时间】:2011-09-27 19:31:19
【问题描述】:

我想以 MVC 方式尽可能地分离表示逻辑和控件:

class MyModel : INotifyPropertyChanged { 

    private IEnumerable<Domain> _domains;
    public IEnumerable<Domain> Domains { 
        get { return _domains; } 
        set { _domains = value; SendPropertyChanged("Domains");
    }
}

class MyControl 
{ 
    // m_Grid's hooked up to m_BindingSource 
    private DataGridView m_Grid;
    private BindingSource m_BindingSouce;
    public void SetModel( MyModel model )
    {
        m_BindingSource.DataSource = model.Domains;
    }
}

class Controller
{
    private MyModel _model;
    private void UpdateDomains()
    {
        // predicate is built on user inputs
        _model.Domains = db.GetDomains( predicate );               
    }
}

// extra code to create Controller, MyModel, and MyControl.  

当 MyModel.Domains 更改时,会触发一个事件以通知 MyControl 其 m_BindingSource.DataSource 已更改。但是,网格不会使用新值进行更新。 为了解决这个问题,MyControl 改为:

class MyControl 
{        
    public void SetModel( MyModel model )
    {
        m_BindingSource.DataSource = model.Domains;
        model.Domains.PropertyChanged += OnDataChanged;          
    }
    private void OnDataChanged(object sender, PropertyChangedEventArgs e)
    {
        BindingSource.DataSource = _model.Data.Users;
    }
}

谁能解释为什么需要这样做? DataBinding 的主要好处之一是减轻程序员管理 PropertyChanged 事件的负担。具有讽刺意味的是,BindingSouce 能够检测 MyModel.Domains 上的更改。我尝试在 m_BindingSource.DataSourceChanged 的​​处理程序中更新 DataSource。更改后,网格停止更新。

【问题讨论】:

  • 我觉得model、view、presenter才是你真正想要的。

标签: c# .net winforms linq datagridview


【解决方案1】:

查看 ObservableCollection http://msdn.microsoft.com/en-us/library/ms668604.aspx 或 BindingList http://msdn.microsoft.com/en-us/library/ms132679.aspx 会有所不同。

顺便说一句,你打错字了(忘记了“r”):

private BindingSource m_BindingSouce; 

【讨论】:

  • BindingList 没有帮助。将看看 ObservableCollection
猜你喜欢
  • 2021-11-06
  • 1970-01-01
  • 2010-11-08
  • 1970-01-01
  • 1970-01-01
  • 2018-01-25
  • 1970-01-01
  • 2017-03-06
  • 1970-01-01
相关资源
最近更新 更多