2017-03-26 28 views
0

我已經擴展了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"; 

} 
+0

你應該寫一個擴展的按鈕類,它將保持對父標籤類的引用 –

+0

爲什麼你不寫一個UserControl? – Steve

回答

2

這看起來像的WinForms,在這種情況下,無論是用戶控件或延長Button類可能是一個很好的路要走 - 只是維持對父項的引用(有點複雜UserControl,您需要定義該控件上的點擊事件,否則您將回到「平方1」)我喜歡Tag屬性解決方案作爲w ell,雖然有一個額外的演員陣容,但不能保證類型安全(因爲Tagobject,當您嘗試訪問它時,它可能是任何東西)。

但是,假設您正在尋找更一般的解決方案;我們還要說有問題的類是sealed,沒有Tag或類似的目的屬性,並且Controls集合不可用(或因循環性能原因而不希望)。據我所知,你不能確定父母的對象;但你可以很容易地提供自己的「控制」式的字典裏,Button映射到父:

public class MyLabel: Label { 
    public static Dictionary<Button, MyLabel> ParentMap = new Dictionary<Button, MyLabel>(); 

    public Button btn; 
    public string mydata; 

    public void AddToParentMap() => ParentMap[btn] = this; 
} 

當你創建的MyLabel一個實例,只需調用AddToParentMap()功能(不能在constructor完成,因爲this指針不可用,直到創建的對象):

MyLabel lbl = new MyLabel(); 
lbl.AddToParentMap(); 

然後你可以只是看它,快速和容易的,在點擊事件:

void button_pressed(Object sender, EventArgs e) { 
    Button btn = (Button)sender; 
    var label = MyLabel.ParentMap[btn]; 

    //... 
    //Your code... 
} 

Tag解決方案不同,保證類型安全 - 您始終知道您正在訪問MyLabel對象。

+0

您已在一篇文章中涵蓋了我所有的疑慮 – Ahmad

0

你不能通過按鈕實例訪問它,但你可以做的是從得到集合:

var lbl = this.Controls.OfType<MyLabel>().FirstOrDefault(c => c.btn == btn); 
0

您可以使用Tag屬性。

lbl.btn = new Button(); 
lbl.btn.Tag = lbl; 

然後當你需要它:

Button btn = (Button)sender; 
Label lbl = (MyLabel)btn.Tag; 
+0

'Label lbl =(MyLabel)btn.Tag;''可以拋出'InvalidCastException',因爲無法保證'Tag'保持不變,因爲它是'object'類型的一般用途屬性。在這種情況下作爲「快速修復」,但不是一個偉大的方法,恕我直言。 – CoolBots

相關問題