我制作了一個具有一些屬性的自定義控制元件(類名稱為 CG):
public int type = 0;
public string control_name { get; set; }
public int decimal_pt { get; set; }
然后在動態創建控制元件時為其分配了一個背景關系選單,如下所示:
void addDevProc(int type)
{
if (type == 0)
{
CG Cont = new CG();
//Right Click settings
MenuItem miprop = cm.MenuItems.Add("Properties");
Cont.ContextMenu = cm;
miprop.Click = devSet;
fcon.Controls.Add(Cont);
}
}
然后我正在呼叫一個對話框來更改上述變數,如下所示:
private void devSet(object sender, EventArgs e)
{
Control_Settings cs = new Control_Settings(fcon, fcon.GetType());
var drDispSettings = cs.ShowDialog();
if(drDispSettings == DialogResult.OK)
{
ControlProps tempProps = new ControlProps();
tempProps = cs._set;
// Transfer Properties to device
switch (tempProps.UnitType)
{
case 0:
CG control = new CG();
control.id = tempProps.UnitAddress;
control.decimal_pt = tempProps.UnitDecimal;
break;
...
}
}
}
這里的 _set 是 ControlProps 型別的屬性。
現在我想根據_set來設定fcon(focussed control)的屬性。
為此我嘗試過:
(fcon as CG).id = tempProps.UnitAddress; // It gives error "Object Reference not set..."
(CG)fcon.id = tempProps.UnitAddress;// Doesn't work "Control dosen't contain defination of id"
如果您能指出我正確的方向,那就太好了。謝謝你的幫助!
編輯1:
fcon(fcon 的型別是 Control)是右鍵單擊的 Control。
CG是一個代表“控制圖形”的類。
ControlProps又是一個具有一些屬性和方法的類,這些屬性和方法適用于我制作的不同型別的自定義控制元件,CG它只是其中之一。我這樣做是因為它們之間有一些共享屬性。
uj5u.com熱心網友回復:
如果fcon不是CG“as”呼叫將回傳null。
你想做的是像
if (fcon is CG cg)
{
cg.id = ...
}
此代碼塊僅在fcon為CG.
您還需要遍歷 fcon 的父級并找到您要查找的控制元件,您可以在此處找到相關資訊,然后在上面的代碼中使用它。
致謝,Reddit 用戶u/lmaydev的答案
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/516761.html
標籤:C#表格
上一篇:如何檢測滑鼠游標是否在圖片框上?
