My code isn’t really that relevant but just to give you background, I have a method that opens an instance of a window messageWindow like this;
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();
}
But I want to see if I can use this method to open other windows as well. This obviously means passing it the name of the new window I want to open as a parameter. My question is, how? I have tried passing parameters like so;
private void SetMessagePosition(Window newWin, Controls.Button btn, string text))
{
newWin = new newWin(text);
...
Where newWin = the type of window I want to open. But obviously the new newWin part throws an error because VS doesn’t know of a window called newWin.
I know your first thought might be, why not just instantiate the windows before calling this method, then I can skip this line all together. Well this method actually sets the position of the new window relative to the parent window at it’s time of opening, ergo, I can’t have set it’s position before now.
Another thing I thought to try was;
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);
...
But newWinType does not like being passed a Type and not a variable, even though it is a list of Type. I would be very impressed if anyone knew a way/workaround to do this.
You need to make it a generic method so you can pass the type:
Then, you can call it like this:
However, the downfall to that approach is that you can’t pass anything into the constructor when you are instantiating an object via a generic type. So, you’d need to set the text on the window in a different way such as creating an interface that has a SetText method, or something like that, and that could be added as another constraint on the generic type.
You could simplify this whole mess by simply expecting the new window to already be instantiated and passed into the method rather than having the method instantiate it itself:
Then, you could just call it like this: