Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a WPF GUI that allows the user to open up an options menu. The option menu opens in a new window and is filled with check boxes. When the user presses the "ok" button the window closes. However, it doesn't remember what check boxes were checked when it is opened back up. How do I make sure the program is able to remember what boxes were checked and which ones weren't?

Just to specify: I only need to remember which boxes are checked during the run of the program. The program does not need to remember after the entire program has been exited.

Thanks!

Here is my code under the main window Window1.XAML.CS:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CartToolsPrototype1
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
           // InitializeComponent();
        }

        //Exit
        private void Exit_Click(object sender, RoutedEventArgs e)
        {
            System.Environment.Exit(0);
        }

        //Options Window - SAVE CHECKED BOXES
        void OpenSettingsWindow()
        {
            var dlg = new Options();
            dlg.DataContext = mGlobalSettings;
            dlg.ShowDialog();
        }

        MySettings mGlobalSettings = new Options();

                                                                /* LANGUAGES **/
        //English Change
        private void English_Click(object sender, RoutedEventArgs e)
        {
            ResourceDictionary dict = new ResourceDictionary();

            dict.Source = new Uri("Lang.en-US.xaml", UriKind.Relative);
            this.Resources.MergedDictionaries.Add(dict);
        }

        //German Change
        private void German_Click(object sender, RoutedEventArgs e)
        {
            ResourceDictionary dict = new ResourceDictionary();

            dict.Source = new Uri("Lang.de-DE.xaml", UriKind.Relative);
            this.Resources.MergedDictionaries.Add(dict);
        }

                                                                /* MAIN MENU **/

        //Options
        private void Options_Click(object sender, RoutedEventArgs e)
        {
            var newWindow = new Options();
            newWindow.Show();
        }
    }
}

Here is my code under the child Window Options.XAML.CS:

I must still be doing something wrong because the compiler says that I need a get or set "accessor".

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CartToolsPrototype1
{
    /// <summary>
    /// Interaction logic for Options.xaml
    /// </summary>
    public partial class Options : Window
    {
        public Options()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }
}

class MySetting : INotifyPropertyChanged
{
    public bool IsSettingSet { get; set; }
}
share|improve this question
Have you considered binding the checkboxes to bool properties in a ViewModel? If you mean the main window closes, you'd need to persist those states in some way; perhaps an xml file. – Killingsworth 2 days ago
1  
Just to be clear, are you trying to keep this persistent even after you restart your entire program? If that's the case, I'd save it to an XML file in your APPDATA folder. – Alex 2 days ago
Just during the run of the program. If the user opens up the options window again I would like to have the same check boxes checked off. – Eric after dark 2 days ago
1  
You can also use settings to save data during the run of the application. – StevenHouben 2 days ago
And how exactly would I do that? – Eric after dark 2 days ago
show 1 more comment

3 Answers

You can use Settings to share data between different Windows/Controls and even save application data when closing/starting an application.

The .NET Framework allows you to create and access values that are persisted between application execution sessions. These values are called settings. Settings can represent user preferences, or valuable information the application needs to use. For example, you might create a series of settings that store user preferences for the color scheme of an application. Or you might store the connection string that specifies a database that your application uses. Settings allow you to both persist information that is critical to the application outside of the code, and to create profiles that store the preferences of individual users.

You can save a Setting in any Window:

Properties.Settings.Default.mySetting = true;
Properties.Settings.Default.Save();

You can read/use a setting in any Window:

this.Property = Properties.Settings.Default.mySetting;
share|improve this answer
This doesn't address the OP's question regarding setting the checkboxes properly when the window is opened, and persisting those settings over the course of the program's run. He specifically mentioned he didn't need to persist between program runs. – Steve 15 hours ago
He can still use settings for that and he edited the question to scope it to a running app after I answered, Captain Obvious. – StevenHouben 8 hours ago

First we need a settings object, that stores our properties. Remember to properly implement INotifyPropertyChanged

class MySettings : INotifyPropertyChanged
{
    public bool IsSettingSet {get;set;}
}

then in our settings window, just use bindings to bind the view controls to your Settings object.

<Window 
    x:Class="SettingsWindow"
    ...>
    <CheckBox IsChecked="{Binding IsSettingSet}"/>
</Window>

and finally where you actually open the window, you need to assign your settings object to the DataContext of your settings window.

class MainWindow
{
    public MainWindow()
    {
        InitializeComponent();
    }
    void OpenSettingsWindow()
    {
        var dlg = new SettingsWindow();
        dlg.DataContext = mGlobalSettings;
        dlg.ShowDialog();
    }

    MySettings mGlobalSettings = new MySettings();
}

now everytime you open the window, your settings will be the same like they were last time. As long as you don't close the application.

share|improve this answer
I have implemented the code, the only build error I am getting has to do with the settings windows' .XAML window. It says that Checked="{Binding IsSettingSet}" is not valid. '{Binding IsSettingSet}" is not a valid event handler method name. Only instance methods on the generated or code-behind class are valid. – Eric after dark 15 hours ago
Checked is an event. The binding should be done with the IsChecked property instead. I've edited @dowhilefor's code example to be a bit more complete. – Steve 15 hours ago
In my opinion, this is the best answer to the question and should be accepted. – Steve 15 hours ago
Yes i'm sorry, that was a typo. – dowhilefor 12 hours ago

If it's just during runtime, then it's pretty easy. You could use a static class:

public static class MyState
{
    public static bool IsChecked1 { get; set; }
}

Or a singleton instance of a class:

public class MyState   
{
   private static MyState _instance = new MyState();

   public static MyState Instance 
   {
      get { return _instance; }
   }

   private MyState() {}

   public bool IsChecked1 { get; set; }

}

When the window loads, get the state from the properties of MyClass. When the window is closing, set the properties of MyClass.

In Options.xaml.cs:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    CheckBox1.IsChecked = MyState.IsChecked1;
}

private void Window_Closed(object sender, EventArgs e)
{
    MyState.IsChecked1 = CheckBox1.IsChecked;
}
share|improve this answer
How would I make sure that code is dedicated to my Options.xaml window? It doesn't really seem like there's anything in that code that would call to the window. – Eric after dark 2 days ago
This of it the other way around - your Options.xaml window would reference the values in MyState when it loads and closes. – RQDQ 2 days ago
Okay, I've implemented the code into my Options.xaml.cs window and tried to make sure that I accounted for all of my check boxes. However, the compiler says that "A get or set accessor expected". Do I need to add something before get and set? I've posted my code, thanks. – Eric after dark 2 days ago
You're very close... You're using the second approach that I recommended. Just do MyState.Instance.IsChecked1 – RQDQ 2 days ago
I added MyState.Instance to every spot that I thought it should go, but anywhere I put it I received an error. I have updated the code and written down the errors. There must be something I'm missing. Thanks. – Eric after dark 21 hours ago
show 6 more comments

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.