SetValue - lucyberryhub/WPF.Tutorial GitHub Wiki

๐ŸŽฏ Update UI with SetValue ๐Ÿ–ผ๏ธโœจ

๐Ÿ‘‹ Hello, future coding masters! Today, weโ€™re going to solve a tricky problem that many programmers face: Why does the screen not update when I change something? ๐Ÿค”


๐Ÿง The Mystery โ€“ Why Doesnโ€™t It Work?

Imagine you have a list of objects displayed on the screen ๐Ÿ“‹, like a list of students in a classroom. Each student has a name and a photo.

Now, you try to change one studentโ€™s photo ๐Ÿ“ท, but nothing happens on the screen!

Why? Letโ€™s investigate! ๐Ÿ•ต๏ธโ€โ™‚๏ธ๐Ÿ”


๐Ÿ’ก The First Way โ€“ The One That Doesnโ€™t Work ๐Ÿšซ

What happens here?

1๏ธโƒฃ You go outside the classroom and find another student with the same name.
2๏ธโƒฃ You give that student a new photo ๐Ÿ–ผ๏ธ.
3๏ธโƒฃ But the student inside the classroom is still the same! They never got the new photo!

๐Ÿ”ด This means the screen doesnโ€™t change!

Code Example (The One That Fails)

// ๐Ÿ” Get a new student object from outside (from the database or file)
var studentList = await LoadStudentsAsync(s => s.Name == "Alice"); 

// ๐Ÿšจ This gets a new copy, NOT the one in the classroom!
var studentOutside = studentList.ToList()[0]; 

// โœ๏ธ Try to change the photo
var property = studentOutside.GetType().GetProperty("Photo");
if (property != null)
{
    property.SetValue(studentOutside, newPhoto);
}

// โŒ The screen does NOT update because studentOutside is NOT the one inside the classroom!

โœ… The Second Way โ€“ The One That Works! ๐ŸŽ‰

What happens here?

1๏ธโƒฃ You walk directly to the student inside the classroom ๐Ÿซ.
2๏ธโƒฃ You give them the new photo. ๐Ÿ“ท
3๏ธโƒฃ The screen immediately updates because you changed the student inside the classroom!

๐Ÿ”ต Now, the change is visible! ๐ŸŽŠ

Code Example (The Correct Way)

// ๐Ÿ” Find the student who is ALREADY inside the classroom (DataGrid)
var studentInside = ClassDataGrid.ItemsSource
    .Cast<StudentModel>()
    .FirstOrDefault(s => s.Name == "Alice");

if (studentInside != null)
{
    // โœ๏ธ Change the photo of the student INSIDE the classroom
    var property = studentInside.GetType().GetProperty("Photo");
    property?.SetValue(studentInside, newPhoto);

    // โœ… Now the screen updates immediately!
}

๐ŸŽฏ What Did We Learn?

โœ… If you want the screen to update, change the thing that is already inside.
โœ… If you create a new one outside, it wonโ€™t be connected to the screen.
โœ… Always update whatโ€™s inside, not a copy of it!


๐Ÿš€ Pro Tips for Future Masters

๐Ÿ’ก Think of it like a notebook ๐Ÿ“– โ€“ if you write something on a new page, but the teacher is looking at the old one, they wonโ€™t see your changes! Change the page the teacher is looking at! ๐ŸŽฏ