-2

today I found a big showstopper for my programming.

There is a class

class Foo
{
    classA property {get; set;}

    classB property {get; set;}

    classC property {get; set;}
}

And each of the classes A, B and C has svereal classes as properties too. So, my class Foo is quite nested. The claas Foo passes parameters to an option window which is opened by the ShowDialog() command.

ShowDialog() result false -> SelectedFoo = backup / result true -> leave method

So if the user cancels the option window the SelectedFoo, which was passed to the ViewModel of the SettingsWindow gets replaced by the backup. Well, in theory. The classes are all reference type and changed duo to the data binding in MVVM. So my backup gets altered too.

How can I stop that behaviour? Is there some way to break the connection between these two classes?

Bob_Foo
  • 23
  • 4
  • 2
    To be clear, you don't have a reference or a connection between two classes -- you have two variables pointing to the same object. When you do `var backup = SelectedFoo;`, you are not creating a copy; you are creating a variable called `backup` that points to the same object that `SelectedFoo` points to. Since there's only one object, any changes you make can be seen using either variable. – asherber Mar 09 '18 at 14:52
  • Are you asking how to [undo](https://stackoverflow.com/questions/3448943/best-design-pattern-for-undo-feature) your changes? – default Mar 09 '18 at 14:59

1 Answers1

2

There's a couple of ways I can think of.

An old pattern from wayback is to deep clone the current settings into a new object and only apply the new settings if the use clicks Apply. This way it won't affect the rest of the system until they "ok" it. If they click Cancel there is nothing to be done because we haven't overwritten anything.

Another slightly more complex alternative is to backup individual properties as required (optionally via reflection). In this mode, no deep clone is required at startup. When a user makes a change, your record the old value before setting the new. If the user decides to cancel, you playback all the changes but this time set the properties to the prior values.

  • Ok, so the easiest way (luckily there is only one SettingsWindow) would be storing each parameter individually? – Bob_Foo Mar 09 '18 at 14:44
  • @Bob_Foo yes. Actually my second example is really not to do with reflection so much but rather backing individual properties as required :) –  Mar 09 '18 at 15:06