【问题标题】:How to save state of checkbox in UserControl c# [duplicate]如何在UserControl c#中保存复选框的状态[重复]
【发布时间】:2017-03-27 00:28:30
【问题描述】:

我正在尝试在我的 UserControl3 上保存复选框的状态。怎么能做到呢?在这我试图通过计时器保存它们。然后在 UserControl3_Load 上添加他们的保存。

private void UserControl3_Load(object sender, EventArgs e)
        {

            materialCheckBox1.Checked = Properties.Settings.Default.CheckBox1;
            materialCheckBox2.Checked = Properties.Settings.Default.CheckBox2;
            materialCheckBox4.Checked = Properties.Settings.Default.CheckBox3;
        }

private void timer1_Tick(object sender, EventArgs e)
        {
            Properties.Settings.Default.CheckBox1 = materialCheckBox1.Checked;
            Properties.Settings.Default.CheckBox2 = materialCheckBox2.Checked;
            Properties.Settings.Default.CheckBox3 = materialCheckBox4.Checked;
            Properties.Settings.Default.Save();
        }

【问题讨论】:

  • 1.使用 CheckChanged/FormClosing 事件而不是计时器 2。你的问题是什么?
  • UserControl 中没有 FormClosing/CheckChanged 事件。问题是它没有保存。
  • 设置的范围是什么?
  • 当您选择(ApplicationSettings)CheckBoxChecked属性时,您创建的设置属性为bool类型。

标签: c# winforms


【解决方案1】:

这很容易。使用User 作为范围。

UserControl1.cs:

    public UserControl1()
    {
        InitializeComponent();
    }

    private void UserControl1_Load(object sender, EventArgs e)
    {
        checkBox1.Checked = Properties.Settings.Default.CheckBox1;
        checkBox2.Checked = Properties.Settings.Default.CheckBox2;
    }

    protected override void OnHandleDestroyed(EventArgs e)
    {
        Properties.Settings.Default.CheckBox1 = checkBox1.Checked;
        Properties.Settings.Default.CheckBox2 = checkBox2.Checked;
        Properties.Settings.Default.Save();
        base.OnHandleDestroyed(e);
    }

【讨论】:

  • 这不是表格。这是一个用户控件。所有材质复选框都存储在用户控件上。
  • 抱歉。它的工作原理相同。
  • 虽然用户控件没有关闭事件。
  • 使用 OnHandleDestroyed 事件。此时您可以完全访问控件的属性,因为它还没有被释放。
  • 如果您使用属性绑定到应用程序设置,您甚至根本不需要Load 中的那些代码,甚至完全可以控制。在您当前的解决方案中,您不会收到设置属性更改的通知并始终显示初始值,而与应用程序设置的数据绑定支持 2 路绑定。有关如何操作的更多信息,请参阅链接的帖子。
猜你喜欢
  • 2013-01-11
  • 1970-01-01
  • 2012-10-01
  • 1970-01-01
  • 2012-04-18
  • 1970-01-01
  • 2018-11-12
  • 1970-01-01
相关资源
最近更新 更多