This might be a trivial question but I am drawing a blank here and can't seem to find the answer online.
Basically, I am trying to create a method that takes 2 properties that are part of an INotifyPropertyChanged
class as parameters (the actual properties to be used in reflection, not the property values), and keep them "in sync" like a binding.
Example
I have a class called Student
with a property called int SemesterScore
. I have another class called Semester
with a property called int Score
. Both of the classes implement IPropertyNotifyChanged
.
Now, let's just assume for a moment that we can't extend any of the classes (as in my real-life scenario) and I may have multiple times in different classes I want to use this.
Basically, I want to be able to call a method in one of my classes that "links" the two properties together.. aka if one of them changes it will auto-update the other.
In non-working code, this is the basic concept:
public class Student : INotifyPropertyChanged
{
private int _semesterScore;
public int SemeseterScore
{
get { return _semesterScore; }
set { [ set property stuff with property changed] }
}
}
public class Semester: INotifyPropertyChanged
{
private int _score;
public int Score
{
get { return _score; }
set { [ set property stuff with property changed] }
}
}
public class Entry
{
public static void Main(string[] args)
{
Student student = new Student();
Semester semester = new Semester();
AttachProperties(student.SemesterScore, semester.Score); // This obviously won't work, but this is where I pass the properties in
semester.Score = 7;
Console.WriteLine(student.SemesterScore); // Output will be 7
}
public static void AttachProperties([sometype] prop1, [sometype] prop2)
{
// Sudo code
prop1.classInstance.PropertyChanged += (pe)
{
if (pe.Property == prop1.Name)
prop2.Value = prop1.Value;
}
prop2.classInstance.PropertyChanged += (pe)
{
if (pe.Property == prop2.Name)
prop1.Value = prop2.Value;
}
}
}
Is there any way to do this? I know some workarounds (aka pass the INotifyPropertyChanged classes and the property names, then do some reflection to get that to work), but the question of passing property instances around (and doing stuff with it) has come up a few times in my coding career.
Thanks!
Nolan
Aucun commentaire:
Enregistrer un commentaire