我已經擴展了Label
類,如下所示:有一個對屬性的引用,有沒有辦法獲取對包含對象的引用?
public class MyLabel: Label {
public Button btn;
public string mydata;
}
在我的主程序,我實例化一個新的實例:
MyLabel lbl = new MyLabel();
lbl.mydata = "some data here";
lbl.btn = new Button();
lbl.btn.Click += new EventHandler(button_pressed);
this.Controls.Add(lbl); // Adds the label to the form
this.Controls.Add(lbl.btn); // Adds the button to the form
我創建了一個方法來處理按鈕單擊事件:
void button_pressed(Object sender, EventArgs e) {
Button btn = (Button)sender;
//Now I have an access to the property within MyLabel instance.
// but how can I access the parent object?
// I need to access the sibling property [mydata] string from here
btn.Siblings["mydata"] = "some other thing" ; //Something like this
MyLabel lbl = btn.ParentObject(); //Or something like this
lbl.mydata = "Some other thing";
}
你應該寫一個擴展的按鈕類,它將保持對父標籤類的引用 –
爲什麼你不寫一個UserControl? – Steve