2017-09-12 112 views
0

我有一個名爲Grid的類,它由另外兩個類CircleLine組成。將屬性綁定到另一個屬性C#

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

我想要的Line的幾何形狀,以保持連接到Circle的幾何形狀。這意味着當我拖動或移動Circle。我想以某種方式通知Line,並根據Circle的新位置更新其幾何圖形。

當然,我總是可以用CircleLine的更新幾何創建新的Grid,但我不想創建新的Grid。我只是想以某種方式將Line的端點綁定到例如Circle的中心。

C#中的哪些技術允許我這樣做?代表? INotifyPropertyChanged的?

+2

您所標記的與你的問題的事實'inotifypropertychanged'意味着你已經知道的回答你的問題。閱讀您在懸停標籤時獲得的鼠標懸停文字。 – Flater

+0

@Flater我不太確定。在這種情況下我不知道如何實現它。 – Vahid

+1

好吧,如果遇到任何問題,請嘗試實施並回到我們這裏。 StackOverflow不是一個代碼寫入服務。 [這是一個官方的MSDN示例](https://docs.microsoft.com/zh-cn/dotnet/framework/winforms/how-to-implement-the-inotifypropertychanged-interface)。您也可以使用谷歌查找一步一步的教程。 – Flater

回答

1
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)); 
    } 
} 

然後在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 
    } 
} 
+0

請注意,這隻有在將Circle(或Line)設置爲Circle(或Line)的**新實例**時纔有效。如果現有的Circle(或Line)的屬性發生更改,則不需要。 – Flater

相關問題