Search code examples
c#winformsclassstatic

How to improve the initialization of a Settings window?


I have a class like this:

public static class Settings
{
    private static SettingsWindow _settingsWindow = null;

    public static void Init(SettingsWindow settingsWindow)
    {
        _settingsWindow = settingsWindow;
    }

Then later is the following (inside a method):

_settingsWindow.ExePathTextBox.Text = CurrentSettings.ExePath;
_settingsWindow.rbSimpleSave.Checked = !CurrentSettings.optSaveUseBrowser;
_settingsWindow.rbBrowserSave.Checked = CurrentSettings.optSaveUseBrowser;
_settingsWindow.rbPresetAll.Checked = CurrentSettings.PreventPresetCol == PC.Allow;
_settingsWindow.rbPresetFolder.Checked = CurrentSettings.PreventPresetCol == PC.Folder;
_settingsWindow.rbPresetGlobal.Checked = CurrentSettings.PreventPresetCol == PC.Global;
_settingsWindow.rbFolderAll.Checked = CurrentSettings.PreventFolderCol == PC.Allow;
_settingsWindow.rbFolderParent.Checked = CurrentSettings.PreventFolderCol == PC.Folder;
_settingsWindow.rbFolderGlobal.Checked = CurrentSettings.PreventFolderCol == PC.Global;

Is there some way to shortcut these statements to avoid repeating _settingsWindow on each line?

I hope there exists some obvious answer which I'm somehow not finding.


Solution

  • IMO, settings the values of form elements is the responsibility of the form itself, not some outside class.
    Therefor, you'd be much better off creating a method in the SettingsWindow class that takes in an instance of (what I'm guessing is) Settings and use that to populate the form:

    // in SettingsWindow
    public void Initialize(Settings currentSettings)
    {
        ExePathTextBox.Text = currentSettings.ExePath;
        rbSimpleSave.Checked = !CurrentSettings.optSaveUseBrowser;
        // do the same for the rest of the form elements 
    }
    

    and then, you can simply call this method from your Settings class:

    // in Settings class
    
    public static void InitializeForm() => _settingsWindow.Initialize(CurrentSettings);