1

我正在开发一个 Excel 2010 模板项目。在我的模板中,我有许多带有静态ListObject控件的工作表。为了初始化 my ListObject,我绑定 aBindingList<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 属性为空。这意味着我无法将数据ListObjectBindingList<MyCustomType>. 我一直在搜索,我发现没有自动的方法来做到这一点,我真的不想制作一段代码来爬过所有的列来重新创建我的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>;
    }
}

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

谢谢。

4

1 回答 1

2

作为最后一个解决方案,我决定在 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 文档中找到有关数据缓存的更多信息。

于 2011-11-17T10:02:02.337 回答