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! ๐ฏ