VSTO Excel:重新打开文件时恢复ListObject数据源

我正在开发Excel 2010模板项目。 在我的模板中,我有很多具有静态ListObject控件的工作表。 为了初始化我的ListObject ,我绑定了一个BindingList<MyCustomType> ,它为我的每个MyCustomType公共属性生成一个列。 这真的很方便,因为当用户在ListObject一些行时,它会自动填充我的BindingList实例。 我在Excelfunction区中添加了一个button,以便程序可以通过EDMvalidation并提交这些行。 这是我如何将我的数据绑定到我的Excel表单的启动事件处理程序中的ListObject。

 public partial class MyCustomTypesSheet { private BindingList<MyCustomType> myCustomTypes; private void OnStartup(object sender, System.EventArgs e) { ExcelTools.ListObject myCustomTypeTable = this.MyCustomTypeData; BindingList<MyCustomType> customTypes = new BindingList<MyCustomType>(); myCustomTypeTable.SetDataBinding(customTypes); } // Implementation detail... } 

现在我的问题是,这个模板的用户很可能会在很多会话中input这些行。 这意味着他将input数据,保存文件,closures它,重新打开它,input一些新的行,并最终在他认为完成时尝试提交这些行。 我注意到,当从模板创build的Excel文件重新打开时,我的ListObject控件的DataSource属性为null。 这意味着我没有办法从ListObject取回数据到BindingList<MyCustomType> 。 我一直在寻找,我发现没有自动的方式来做到这一点,我真的不想做一段代码,将通过所有列爬行重新创build我的MyCustomType实例。 在理想的世界里,我会这样做。

 private void OnStartup(object sender, System.EventArgs e) { ExcelTools.ListObject myCustomTypeTable = this.MyCustomTypeData; BindingList<MyCustomType> customTypes = null; if (myCustomTypeTable.DataSource == null) // Will always be null and erase previous data. { customTypes = new BindingList<MyCustomType>(); myCustomTypeTable.SetDataBinding(customTypes); } else { customTypes = myCustomTypeTable.DataSource as BindingList<MyCustomType>; } } 

我一直在做很多的研究,但是我找不到解决scheme,所以我希望你们有些人可以帮我解决这个问题。

谢谢。

作为最后一个解决scheme,我决定将序列化XML中的对象列表,然后将其作为XML自定义部分添加到保存的Excel文件中。 但是当我进入MSDN文档来实现这一点时,我发现有两种方式来保存数据:XML自定义部分和数据caching。 而实际上,数据caching正是我正在寻找的function。

所以我只能使用CachedAttribute来实现我的目标。

 public partial class MyCustomTypesSheet { [Cached] public BindingList<MyCustomType> MyCustomTypesDataSource { get; set; } private void OnStartup(object sender, System.EventArgs e) { ExcelTools.ListObject myCustomTypeTable = this.MyCustomTypeData; if (this.MyCustomTypesDataSource == null) { this.MyCustomTypesDataSource = new BindingList<MyCustomType>(); this.MyCustomTypesDataSource.Add(new MyCustomType()); } myCustomTypeTable.SetDataBinding(this.MyCustomTypesDataSource); } private void InternalStartup() { this.Startup += new System.EventHandler(OnStartup); } } 

它像一个魅力。 您可以在MSDN文档中find有关数据caching的更多信息。