0

So my problem is as follows:

I am passing an object called Items of class MyClass into a new instance of MyWindow in WPF. And I am passing by value, not by reference. Then I bind certain controls (textboxes, comboboxes, etc.) of MyWindow to the properties of a new field called ItemsReplicate of MyClass that belongs to MyWindow and is made equal to Items. However, when I make changes to any control in MyWindow, Items's properties get overwritten too for some reason. Is this normal? Or am I missing out on something?

Here's the code description:

var passThis = (MyClass)myItem;
MyWindow wnd = new MyWindow(passThis);

public partial class MyWindow : Window
{
    public MyWindow (MyClass _item)
    {
        InitializeComponent();
        innerItem = _item;
        this.DataContext = innerItem ;
    }

    private MyClass innerItem;
}

So in the end of this procedure, any changes made via binding affects both myItem and innerItem

Many thanks.

PS: Binding mode: Two-way

O. Odabasi
  • 11
  • 1

1 Answers1

0

Edited after comment.

Default parameter passing for classes is per reference, even without the "ref" keyword, which only makes changes to the reference of the object itself visible "on the outside".

MyClass c = new MyClass();

MyMethod(c);
MyRefMethod(ref c);

public void MyMethod(MyClass innerc)
{
    innerc = new MyClass(); //stays local, c is still its old reference
}

public void MyRefMethod(ref MyClass innerc)
{
    innerc = new MyClass(); //c becomes a new reference to the local innerc
}

As in your case: You pass a copy of the reference to MyClass as '_item'. You then store that reference-copy in 'innerItem' as well as in the DataContext. It is still only one Instance of MyClass with multiple reference-copies. Every copy of a reference just points to the same instance of the class.

When you modify the values of your public properties of MyClass with the binding in WPF, the values inside of your original instance of MyClass are getting an update.

In other words: This is normal behavior.

If you really want a deep copy of your Class, the easiest way is to serialize and desialize it.

Andreas
  • 828
  • 4
  • 15
  • Many thanks for your response! Yet what I have done (please see the edited version of my question with the added codes) is something different. – O. Odabasi Feb 14 '18 at 09:59
  • That's still the same in the way, that you don't hand over a copy of MyClass but a reference to the same copy. Therefore it is still normal behavior and identical to the MyMethod. My "ref"- explanation was just to make another point clear. In both cases you pass a reference, as well as in your code snippet. – Andreas Feb 14 '18 at 11:29
  • Thank you for the explanation. I wasn't aware of this. I managed to get around the problem by creating a deep clone of the class instance as you pointed out (shallow copy didn't cut it). Cheers. – O. Odabasi Feb 15 '18 at 15:34