简体   繁体   中英

C# WPF Received object from ListBox.selectedItem is able to modify itemSource collection, how?

I'm new to C# and WPF, so please don't roast me to hard :)

I have an ObservableCollection<> of many objects which I show in a ListBox by using

MyListBox.ItemsSource = MyObservableCollection;

The goal now is to change the selected item, so what I'm doing is the following:

MyClass selectedObject = MyListBox.SelectedItem as MyClass;

Now I can just say something like selectedObject.Name = "Something" and of cause the value of selectedObject.Name gets changed. But to my surprise the value gets also changed in my original ObservabalCollection object ("MyObservableCollection").

This is exactly what I want, but tbh I don't understand why and how this works. How is selectedObject connected to the original object inside the ObservableCollection?

Further on im passing selectedObject as an argument to a new window, for doing the editing inside this new window:

EditObject editObject = new EditObject(selectedObject);

Even in the new window I can just asign new values to selectedObject and they get changed in my ObservableCollection too.

Can someone explain this behavior to me? :)

Thank you!

MyListBox.SelectedItem is a reference to the object in your observable collection. See https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/reference-types

If you pass the reference of this object to another window and modify it there it should also change in the original ObservableCollection.

int for instance is not a reference type and will pass by value. It won't change in the original location.

Try this example:

class Program
{
    static void Main(string[] args)
    {
        TestClass testClass = new TestClass();
        Console.WriteLine(testClass.number);
        ChangeTest(testClass);
        Console.WriteLine(testClass.number);

        int i = 0;
        Console.WriteLine(i);
        ChangeInt(i);
        Console.WriteLine(i);


        Console.ReadKey();
    }

    public static void ChangeTest(TestClass t)
    {
        t.number++;
    }

    public static void ChangeInt(int i)
    {
        i++;
    }
}



public class TestClass
{
    public int number = 0;
}

Will give you this output:

0
1
0
0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM