yas4891
yas4891

Reputation: 4862

.NET WinForms PropertyBinding

I have a WinForm with a menu bar, a menu and a menuItem (called BlaBlub).
the menu item has CheckOnClick = True and (ApplicationSettings)->(PropertyBindings)->Checked mapped to the setting SomeBool (type bool, scope user, initial value= false)

the value is read correctly from the settings-file (i use a label to check it and also the menu item gets selected/deselected when I make changes to the file between sessions).

However, using the following code I was not able to open the application, click on the menu item and store the changed value back into file

    private void Form1_FormClosed(object sender, FormClosedEventArgs e)
    {
        Properties.Settings.Default.Save();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        label1.Text = string.Format("Value is: {0}", Properties.Settings.Default.SomeBool);
    }

I was able to store the value back into file, using the following code, but since this does not seem to be the idiomatic approach, I still seek some enlightment as to how to do this.

    private void blaBlubToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
    {
        Properties.Settings.Default.SomeBool = blaBlubToolStripMenuItem.Checked;
    }

Upvotes: 0

Views: 1109

Answers (1)

Reddog
Reddog

Reputation: 15579

You said:

the value is read correctly from the settings-file

However, based on the code presented, that wouldn't be correct because on load you aren't setting the checked state. Instead, I think your testing is showing the initial persisted setting value (being false) is also the default Checked state for the menu item.

Therefore, you should also intialize the control too by adding:

private void Form1_Load(object sender, EventArgs e)
{
    label1.Text = string.Format("Value is: {0}", Properties.Settings.Default.SomeBool);
    blaBlubToolStripMenuItem.Checked = Properties.Settings.Default.SomeBool;
}

Note: Ordinarily I would tell you to use databinding but you can't because I believe MenuItem's do not support this.

Upvotes: 1

Related Questions