2016-02-19 36 views
0

myUserControl包含兩個控件。 A textbox和標籤。此用戶控件位於類庫對象中。它將用於其他幾個項目。用戶控制數據綁定不能正常工作

我會像這樣綁定。

myControl1.Databindings.Add("DataSource",myObject,"PropertyName"); 

這裏,PropertyName將直接與文本結合(這我全成),我已經在myObject定義的屬性來獲得使用PropertyName標籤名稱。所以雖然userControl設置標籤和文本框,但它需要整個綁定來綁定標籤和文本框數據。

我所做的是這裏(控制):

private object dataSource; 
    [DefaultValue("")] 
    public Object DataSource 
    { 
     get 
     { 
      return dataSource; 
     } 
     set 
     { 
      dataSource = value; 

      OnPropertyChanged(new PropertyChangedEventArgs("DataSource")); 
      BindControls(); 
      if (dataSource != null) 
      { 
       textBox1.Text = dataSource.ToString(); 
      } 

     } 
    } 

    //Method to bind datasource with controls 
    public void BindControls() 
    { 
     if (this.DataBindings.Count > 0) 
     { 
      //Get the instance of the binded object 
      object myObj = this.DataBindings[0].DataSource as object; 

      //Get binded field name as string 
      string bindingField = this.DataBindings[0].BindingMemberInfo.BindingField; 

      //Get Type of the binded object 
      Type t1 = myObj.GetType(); 

      //Get property information for the binded field 
      PropertyInfo property = t1.GetProperty(bindingField); 

      //Get text value for label 
      LabelText = property.GetAttribute<DisplayNameAttribute>(false).DisplayName; 
      textBox1.ForeColor = Color.Black; 
      //If textbox data is null or empty, get descrition or comment as the textbox text. 
      if (string.IsNullOrEmpty(dataSource.ToString())) 
      { 
       dataSource = property.GetAttribute<DescriptionAttribute>(false).Description; 
       textBox1.ForeColor = Color.DarkGray; 
      } 
     } 
    } 

因爲當我綁定在那裏我使用這個控制從表格數據源第一次,標籤文本爲空,但文本包含正確的價值。我發現的原因是,DataBinding仍然是空的。

在我的表單中,我使用了一個複選框來切換對象值。當我檢查這個值時,Usercontrol獲得數據綁定,然後所有的事情都進行正確。

回答

0

問題出在您正在提升的propertychange。 該字符串應該與屬性名稱相同。 試試這樣的......

public string Name 
     { 
      get { return m_Name; } 
      set 
      { 
       if (m_Name != value) 
       { 
        m_Name = value; 
        OnChange("Name"); 
       } 
      } 
     } 
+0

因爲我的對象是''DataSource'''和它的相同,我想。數據源正在獲取綁定值(看看我的綁定屬性),但我沒有第一次獲得完整的綁定對象。那是我的問題 –