我的代碼並不是真的那麼相關,只是爲了給你背景,我有一個方法可以打開窗口的實例messageWindow
這樣;傳遞窗口/類型作爲參數
private void SetMessagePosition(Controls.Button btn, string text)
{
messageWindow = new messageWindow(text);
relativePoint = btn.TransformToAncestor(this).Transform(new Point(0, 0));
messageWindow.Left = relativePoint.X + this.Left;
messageWindow.Top = relativePoint.Y + this.Top;
messageWindow.Show();
}
但我想看看我是否也可以用這種方法打開其他窗口。這顯然意味着將我想要打開的新窗口的名稱作爲參數傳遞給它。我的問題是,如何?我曾嘗試傳遞參數像這樣;
private void SetMessagePosition(Window newWin, Controls.Button btn, string text))
{
newWin = new newWin(text);
...
其中newWin
=我想要打開的窗口的類型。但顯然new newWin
部分會拋出一個錯誤,因爲VS不知道名爲newWin
的窗口。
我知道你的第一個想法可能是,爲什麼不在調用這個方法之前實例化窗口,那麼我可以一起跳過這一行。那麼這個方法實際上設置了新窗口在打開時相對於父窗口的位置,ergo,我現在不能設置它的位置。
我想要嘗試的另一件事是;
List<Window> winList;
List<Type> winListType;
winList.Add(window1);
winList.Add(window2);
winList.Add(window3);
winListType.Add(Window1);
winListType.Add(Window2);
winListType.Add(Window3);
SetMessagePosition(winList[2], winListType[2], btn1, "Yes");
private void SetMessagePosition(Window newWin, Type newWinType, Controls.Button btn, string text))
{
newWin = new newWinType(text);
...
但newWinType
不喜歡被通過的Type
,而不是一個變量,即使它是Type
列表。如果有人知道這樣做的方式/解決方法,我會非常感動。
更靈活我建議使用接口,而不是窗口和類型 – HichemSeeSharp
@HichemC道歉,但我沒有接口的知識。現在將閱讀他們。 – windowskm