【问题标题】:VSTO Excel: Restore ListObject data source when reopening a fileVSTO Excel:重新打开文件时恢复 ListObject 数据源
【发布时间】:2011-12-29 11:50:41
【问题描述】:

我正在处理一个 Excel 2010 模板项目。在我的模板中,我有很多张带有静态ListObject 控件的表格。为了初始化我的ListObject,我绑定了一个BindingList<MyCustomType>,以便它为我的每个MyCustomType 公共属性生成一个列。这真的很方便,因为当用户在ListObject 中有一些行时,它会自动填满我的BindingList 实例。我在 Excel 功能区中添加了一个按钮,以便程序可以通过 EDM 验证和提交这些行。这就是我将数据绑定到我的一张 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...
}

现在我的问题是该模板的用户很可能会在许多会话中输入这些行。这意味着他将输入数据,保存文件,关闭它,重新打开它,输入一些新行,并最终在他认为完成时尝试提交这些行。我注意到,当重新打开从模板创建的 Excel 文件时,我的 ListObject 控件的 DataSource 属性为空。这意味着我无法将ListObject 中的数据取回BindingList&lt;MyCustomType&gt;。我一直在搜索,我发现没有自动的方法来做到这一点,我真的不想制作一段代码来爬过所有的列来重新创建我的 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>;
    }
}

我已经对此进行了大量研究,但我无法找到解决方案,所以我希望你们中的一些人可以帮助我解决这个问题。

谢谢。

【问题讨论】:

    标签: excel data-binding vsto datasource listobject


    【解决方案1】:

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

    所以我已经能够通过简单地使用 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 documentation 中找到有关数据缓存的更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-05
      • 1970-01-01
      • 2013-03-15
      • 1970-01-01
      相关资源
      最近更新 更多