2009-03-03 148 views
7

我有一個自定義控件(Windows窗體),它是一個查找文本框。控件上的一個屬性是當前選擇,它是一個包含「標識符」,「代碼」和「描述」的自定義對象。該屬性是使用BindingSource的Databound。數據綁定自定義控件

顯示信息的效果很好。另一方面,無論我將更新設置爲OnValidate還是OnValueChange,它都不會更新BindingSource。有什麼我想念得到這個自動更新?

private System.Windows.Forms.BindingSource buildPlanComponentDataBindingSource; 

    public void LoadBuildPlan(string itemNumber) 
    { 
     var buildPlanComponents = BuildPlan.LoadBuildPlanComponents(itemNumber, AutomaticPrice); 
     buildPlanComponentDataBindingSource.DataSource = buildPlanComponents; 
     AssemblyNumber = itemNumber; 
    } 




[Bindable(true)] 
[DefaultValue(null)] 
public ILookupSelection CurrentSelection 
{ 
    get 
    { 
     if (currentSelection == null) 
      currentSelection = new LookupSelection {Code = txtLookup.Text}; 

     return currentSelection; 
    } 

    set 
    { 
     if (value == null) return; 

     currentSelection = value; 

     SetText(currentSelection, DisplayText); 
     SetDescription(currentSelection, DisplayDescription); 
    } 
} 
+0

你能告訴我們你創建數據綁定的代碼嗎? – overslacked 2009-03-03 16:44:24

+0

謝謝,你的問題是非常有幫助的。出於某種原因,MSDN教程忽略了其教程中的[Bindable(true)]屬性。這是一個重要的細節! – 2016-05-13 15:21:24

回答

2

實施INotifyPropertyChanged似乎是解決方案!

#region IPropertyChanged 

    public event PropertyChangedEventHandler PropertyChanged; 

    protected virtual void OnPropertyChanged(string propertyName) 
    { 
     OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); 
    } 

    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) 
    { 
     if (null != PropertyChanged) 
     { 
      PropertyChanged(this, e); 
     } 
    } 

    #endregion 
0

顯示信息工程 很大。另一方面,不管 是否將更新設置爲OnValidate 或OnValueChange,它都不會更新 BindingSource。

看着你的代碼我其實不確定這一點。在你的集合中,你測試null和放棄;如果數據實際上包含null(這就是你所描述的),那麼你的控件將不同步。我想知道這個檢查是否掩蓋了潛在的問題。

+0

真正爲NULL的唯一時間是最初創建控件時。否則,只有當選擇包含一個值時纔會設置。 – ejmack 2009-03-03 16:58:27

0

也許你需要讓DataBinding爲每個控件設置它的值,而這個控件的值是以這種方式設置的?

假設一個數據名爲txtMySetValue文本框結合:

txtMySetValue.DataBindings [0] .WriteValue();