Master Detail数据绑定与ComboBox详细信息[WinForms]

时间:2013-11-01 20:26:51

标签: winforms data-binding

尝试设置主细节方案,其中详细信息将包含组合框。有没有办法让每个细节项目使用纯数据绑定保留其选择,或者是否需要在此处完成一些手动管道。

以下示例的重新创建步骤:

  1. 将M1的详细信息更改为“Detail2”
  2. 切换到主M2,然后返回M1
  3. 详细信息将恢复为Detail1。我希望它能保留之前选择的值
  4. 表单构造函数:

    InitializeComponent ();
    
    List<MasterData> dataList = new List<MasterData> ();
    
    dataList.Add (new MasterData ("M1"));
    dataList.Add (new MasterData ("M2"));
    
    // master data
    this.masterBindingSource.DataSource = typeof (MasterData);
    this.masterBindingSource.DataSource = dataList;
    
    this.masterComboBox.DataSource = this.masterBindingSource;
    this.masterComboBox.DisplayMember = "Name";
    
    // details                    
    this.detailsBindingSource.DataMember = "Details";
    this.detailsBindingSource.DataSource = this.masterBindingSource;
    
    this.detailsComboBox.DataBindings.Add (new System.Windows.Forms.Binding ("SelectedValue", this.masterBindingSource,
        "SelectedDetail", true));
    
    this.detailsComboBox.DataSource = this.detailsBindingSource;
    this.detailsComboBox.DisplayMember = "Name";
    
    // Label to make sure the master is actually changing
    this.detailLabel.DataBindings.Add (new System.Windows.Forms.Binding ("Text", this.masterBindingSource, 
        "Name", true, DataSourceUpdateMode.OnPropertyChanged));
    

    数据:

    public class Details
    {
        public String Name { get; set; }
    
        public Details (string name)
        {
            this.Name = name;
        }
    }
    
    public class MasterData
    {
        public String Name { get; set; }
        public List<Details> Details { get; set; }
        public Details SelectedDetail { get; set; }
    
        public MasterData (string name)
        {
            this.Details = new List<Details> ();
            this.Name = name;
    
            this.Details.Add (new Details ("Detail1"));
            this.Details.Add (new Details ("Detail2"));
            this.SelectedDetail = this.Details.FirstOrDefault ();
        }
    }
    

    我来自WPF背景并努力理解WinForms中的绑定,希望这一切都有意义。

0 个答案:

没有答案