2011-05-17 99 views
1

環境:的Visual Studio 2010,.NET 4.0,WinForms的綁定Checkbox.Checked財產財產上的DataSet

我有一個實現INotifyPropertyChanged的一個DataSet,並創造了在DataSet中的布爾屬性。我試圖綁定一個CheckBox.Checked屬性到bool屬性。當我嘗試在設計器中完成它時,我會看到數據集中的數據集和表格,但不是屬性。我試圖手動執行該操作,但收到該屬性未找到的錯誤。唯一不同的是,我看到我正在做的是表單上的屬性是被實例化的數據集的超類,但我甚至都沒有看到這會如何影響任何東西。代碼片段如下。

派生類定義

public class DerivedDataSetClass: SuperDataSetClass, INotifyPropertyChanged 
{ 
    private bool _mainFile = false; 
    public bool MainFile 
    { 
    get { return this._mainFile; } 
    set { 
     this._mainFile = value; 
     this.NotifyPropertyChanged("MainFile"); 
    } 
    } 
} 

屬性定義

private SuperDataSetClass _dataSet; 
public DerivedDataSetClass DataSet 
{ 
    get { return (DerivedDataSetClass)_dataSet; 
} 

男星

this._DataSet = new DerivedDataSetClass (this); 

this.mainFileBindingSource = new BindingSource(); 
this.mainFileBindingSource.DataSource = typeof(DerivedDataSetClass); 
this.mainFileBindingSource.DataMember = "MainFile"; 

var binding = new Binding("Checked", this.mainFileBindingSource, "MainFile"); 
this.chkMainFile.DataBindings.Add(binding); 

的思考?

回答

1

問題直接來自您想要使用您的方式DerivedDataSetClass。由於它是DataSet,所有已完成的綁定都將使用其默認的DataViewManager,其中「推送」進一步綁定到Tables綁定。

當您綁定到DerivedDataSetMainFile財產,什麼被引擎蓋下做的是綁定到一個名爲數據集表中MainFile表的嘗試。當然這會失敗,除非你真的在數據集中有這樣的表格。出於同樣的原因,您不能綁定的任何其他財產的基地DataSet - 例如。 LocaleHasErrors - 它還檢查這些表是否存在,而不是屬性。

這個問題的解決方案是什麼?您可以嘗試實施不同的DataViewManager - 但我無法找到有關該主題的可靠資源。

我建議什麼是您MainFile屬性創建簡單的包裝類及相關DerivedDataSetClass,像這樣的:你的包裝

public class DerivedDataSetWrapper : INotifyPropertyChanged 
{ 
    private bool _mainFile; 

    public DerivedDataSetWrapper(DerivedDataSetClass dataSet) 
    { 
     this.DataSet = dataSet; 
    } 

    // I assume no notification will be needed upon DataSet change; 
    // hence auto-property here 
    public DerivedDataSetClass DataSet { get; private set; } 

    public bool MainFile 
    { 
     get { return this._mainFile; } 
     set 
     { 
      this._mainFile = value; 
      this.PropertyChanged(this, new PropertyChangedEventArgs("MainFile")); 
     } 
    } 
} 

現在可以綁定到這兩個數據集內的內容(表)以及MainFile類。

var wrapper = new DerivedDataSetWrapper(this._DataSet); 
BindingSource source = new BindingSource { DataSource = wrapper }; 

// to bind to checkbox we essentially bind to Wrapper.MainFile 
checkBox.DataBindings.Add("Checked", source, "MainFile", false, 
    DataSourceUpdateMode.OnPropertyChanged); 

要綁定從數據集中的表中的數據,您需要綁定到DerivedDataSetWrapperDataSet屬性,然後通過表名和列導航。例如:

textBox.DataBindings.Add("Text", source, "DataSet.Items.Name"); 

...將綁定到您的原始_DataSet中的表Items和列Name

+0

不幸的是,這並沒有幫助。當表單嘗試顯示時,我得到一個invalidargument異常,該屬性MainFile無法綁定到System.Forms的CheckBindings方法中。 – 2011-05-18 04:53:05

+0

@ wraith808:是的,我轉載了你的問題。它來自DataSet'綁定完成的事實 - 檢查我的編輯。 – 2011-05-18 10:52:26

+0

感謝您的信息!我試圖繞過使用CheckBox點擊方法,但考慮到開銷和事實,這是一個現有的應用程序,我想這是更清潔。但我很高興知道原因,解決方法,並且我對所看到的並不瘋狂。 ;) – 2011-05-18 18:05:23