You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何重置DevExpress pivotGridControl设置 跨窗体调用RestoreLayoutFromRegistry不生效

问题根因
  • butReset_Click 被设置为静态方法,无法关联当前正在运行的Form1窗体实例,且方法内部重新new Form1()生成了一个不可见的全新窗体对象,操作的不是用户界面上正在使用的窗体,因此重置操作不会在可见界面生效
  • 你在二级弹出窗体中直接使用了Form1类的全局按钮实例,事件绑定逻辑和实际需要操作的pivotGridControl所属窗体实例不匹配
修复实现

首先调整事件方法的修饰符,取消静态声明,直接操作当前实例的控件,同时修改二级窗体的按钮绑定逻辑,绑定当前窗体的重置方法即可,修改后代码如下:

namespace WindowsFormsApp4
{
    public partial class Form1 : Form
    {
        string regKey = "DevExpress\\XtraPivotGrid\\Layouts\\PivotGridLayout";
        public Form1()
        {
            InitializeComponent();
            // 初始保存默认布局,用于重置恢复
            pivotGridControl1.SaveLayoutToRegistry(regKey);
        }

        public void LoadBtn_Click(object sender, EventArgs e)
        {
            // 创建二级窗体
            Form form = new Form();
            ListBox listBox1 = new ListBox();
            listBox1.Size = new System.Drawing.Size(200, 100);
            listBox1.Location = new System.Drawing.Point(10, 10);
            form.Controls.Add(listBox1);
            listBox1.MultiColumn = true;
            listBox1.SelectionMode = SelectionMode.MultiExtended;

            DirectoryInfo dir = new DirectoryInfo(@"E:\");
            FileInfo[] files = dir.GetFiles("*.txt");

            // 二级窗体单独创建按钮实例,不要复用全局按钮避免冲突
            Button butResetSub = new Button();
            butResetSub.Text = "重置设置";
            butResetSub.Location = new Point(140, 160);
            // 绑定当前实例的重置方法,操作当前窗体的pivotGridControl
            butResetSub.Click += new System.EventHandler(butReset_Click);
            form.Controls.Add(butResetSub);

            Button butLoadSub = new Button();
            butLoadSub.Text = "确认";
            butLoadSub.Location = new Point(30, 160);
            form.Controls.Add(butLoadSub);

            var fileNamesWithoutExtension = files
                .Select(fi => Path.GetFileNameWithoutExtension(fi.Name));
            foreach (string fn in fileNamesWithoutExtension)
            {
                listBox1.Items.Add(fn.ToString());
            }
            form.Show();
        }

        private void SaveBtn_Click(object sender, EventArgs e)
        {
            pivotGridControl1.RestoreLayoutFromRegistry(regKey);
        }

        // 移除static修饰符,直接操作当前实例的控件
        public void butReset_Click(object sender, EventArgs e)
        {
            // 直接操作当前窗体的pivotGridControl,不需要新建Form1实例
            pivotGridControl1.RestoreLayoutFromRegistry(regKey);
        }
    }
}
核心修改说明
  • 移除了butReset_Click方法的static修饰符,方法内直接访问当前窗体实例的pivotGridControl1控件进行重置
  • 二级弹出窗体内单独创建按钮实例,绑定当前窗体的重置事件,保证两个窗体触发的重置操作都作用在同一个pivotGridControl所在的窗体上
  • 移除了无意义的新Form1实例创建逻辑,避免操作对象错误

内容的提问来源于stack exchange,提问作者ebw1910

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 21:36:06