Writing a Supported Commit Method

I have a ViewModel that encapsulates some properties that are editable in the options dialog. I can't actually save them in preferences until they click OK, which will eventually cause Commit on that particular ViewModel.

The only property in my ViewModel looks like this:

public bool SomeProperty
{
    get
    {
        return m_SomeProperty;
    }
    set
    {
        if (m_SomeProperty != value)
        {
            m_SomeProperty = value;
            NotifyPropertyChanged("SomeProperty");
        }
    }
}
private bool m_SomeProperty = Properties.Settings.Default.SomeProperty;

      

So a normal Commit implementation would be:

public void Commit()
{
    Properties.Settings.Default.SomeProperty = m_SomeProperty;
    // Add other properties here...
}

      

It's not that bad, but the reason I don't like it is that if you add a new property, you need to add the code for it in two places. I try to avoid this whenever possible.

At first I thought I could declare a private OnCommit event and apply the Commit method for this event, and the code for each property add an event handler for the event and write it to the settings there, but I don’t know I don’t know how to do this without adding event handlers into the constructor anyway, which doesn't help the situation.

Any ideas? Does anyone have an elegant way to do what I am trying to do?

EDIT : Thanks to the six digit variables for the answer. I took this idea and incorporated it into SoapBox Core and opened the result. Check out the Options dialog box to see how it works.

+2


source to share


2 answers


Is there a run-list supported Action

?

private List<Action> commitActions = new List<Action>();

public bool SomeProperty
{
    get
    {
        return m_SomeProperty;
    }
    set
    {
        if (m_SomeProperty != value)
        {
            m_SomeProperty = value;
            lock (commitActions)
            {
                commitActions.Add(
                    () => Properties.Settings.Default.SomeProperty = value);
            }
            NotifyPropertyChanged("SomeProperty");
        }
    }
}

      



Then update your code Commit

to run the loop.

public void Commit()
{
    List<Action> commits;
    lock (commitActions)
    {
        commits = new List<Action>(commitActions);
        commitActions.Clear();
    }

    foreach (var commit in commits)
    {
        commit();
    }
}

      

+4


source


Could you use reflection to figure out what properties your class has and iterate over them?



0


source







All Articles