C# 動態生成物件與其他物件綁定


我的使用情境是點擊動態生成的圖片會做出相應動作
但是這個動作必須與他一起生成的Label等其他物件有關連
所以可以使用以下方法

打包成一個自訂的元件
並將元件與生成的圖片做關聯

var pictureBoxLabelPair = new Tuple<PictureBox, Label>(pictureBox, label);
pictureBox.Tag = pictureBoxLabelPair;

之後在處理事件的地方將關聯的物件存取到新的物件
這樣就可以拿取或控制想要的物件了

PictureBox clickedPictureBox = (PictureBox)sender;
var pictureBoxLabelPair = (Tuple<PictureBox, Label>)clickedPictureBox.Tag;
Label label = pictureBoxLabelPair.Item2;

第二種方式就是用class

class MyData
{
    public int IntValue { get; set; }
    public string StringValue { get; set; }
    public bool BoolValue { get; set; }
    public double DoubleValue { get; set; }
}
var data = new MyData
{
    IntValue = 42,
    StringValue = "Hello, World!",
    BoolValue = true,
    DoubleValue = 3.14
};
var pictureBoxLabelPair = (MyData)clickedPictureBox.Tag;
#C# #Winform







你可能感興趣的文章

Event Capture, Propagation, Bubbling and Once

Event Capture, Propagation, Bubbling and Once

畫frequency response和phase response(MATLAB))

畫frequency response和phase response(MATLAB))

CS50 TCP (Transmission Control Protocol)

CS50 TCP (Transmission Control Protocol)






留言討論





2
2
2