Creating a bindable Point in C# WPF

后端 未结 4 2103
执念已碎
执念已碎 2021-02-15 23:51

I know multiple inheritence is out, but is there a way to create a wrapper for System.Windows.Point that can inherit from it but still implement bindable dependency properties?<

4条回答
  •  佛祖请我去吃肉
    2021-02-16 00:04

    1. Write a wrapper class for point which implements the INotifyPropertyChanged interface

      public class BindingPoint : INotifyPropertyChanged
      {
          private Point point;
      
          public BindingPoint(double x, double y)
          {
              point = new Point(x, y);
          }
      
          public double X
          {
              get { return point.X; }
              set
              {
                  point.X = value;
                  OnPropertyChanged();
                  OnPropertyChanged("Point");
              }
          }
      
          public double Y
          {
              get { return point.Y; }
              set
              {
                  point.Y = value;
                  OnPropertyChanged();
                  OnPropertyChanged("Point");
              }
          }
      
          public Point Point
          {
              get { return point; }
          }
      
          public event PropertyChangedEventHandler PropertyChanged;
      
          [NotifyPropertyChangedInvocator]
          protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
          {
              var handler = PropertyChanged;
              if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
          }
      }
      
    2. Bind startpoint / endPoint X and Y properties for example to a line instance

      Line line = new Line();
      BindingPoint startPoint = new BindingPoint(0,0);
      BindingPoint endPoint = new BindingPoint(0,0);
      
      var b = new Binding("X")
      {
          Source = startPoint,
          Mode = BindingMode.TwoWay
      };
      line.SetBinding(Line.X1Property, b);
      
      b = new Binding("Y")
      {
          Source = startPoint,
          Mode = BindingMode.TwoWay
      };
      line.SetBinding(Line.Y1Property, b);
      
      b = new Binding("X")
      {
          Source = endPoint,
          Mode = BindingMode.TwoWay
      };
      line.SetBinding(Line.X2Property, b);
      
      b = new Binding("Y")
      {
          Source = endPoint,
          Mode = BindingMode.TwoWay
      };
      line.SetBinding(Line.Y2Property, b);
      

提交回复
热议问题