Search code examples
c#data-bindingpropertiesdelegatesinotifypropertychanged

Bind a property to another property in C#


I have a Class called Grid that is composed of two other classes: Circle and Line. Here is the code for these classes:

public class Grid
{
    public Circle Circle {get; set;}
    public Line Line {get; set;}
}

I want the geometry of Line to stay connected to the geometry of the Circle. This means that when I move the Circle, I want the Line to be notified and update its geometry to match the new location of the Circle. I could create a new Grid with the updated geometries of the Circle and Line, but I don't want to create a new Grid. Instead, I want to bind the endpoints of the Line to the Circle, for example to its center.

What technologies in C# can I use to achieve this? Are delegates or the INotifyPropertyChanged interface suitable for this purpose?


Solution

  • public class Circle : INotifyPropertyChanged
    {
        private int radius;       
        public int Radius 
        {
            get { return radius; }
            set 
            {
                radius = value;
                RaisePropertyChanged("Radius");
            }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        private void RaisePropertyChanged(string propertyName)
        {
            var propChange = PropertyChanged;
            if (propChange == null) return;
            propChange(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    

    Then in Grid.cs

    public class Grid
    {
        private Circle circle;
        public Circle Circle 
        {
           get { return circle; }
           set 
           {
               circle = value;
               if (circle != null) 
                  circle.PropertyChanged += OnPropertyChanged;
           }
        }
    
        private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "Radius")
                // Do something to Line
        }
    }