Reputation: 2381
I have a custom built menu system in which I would like to load user controls from another project into a tab control on my main project (menu control)
User control Project : foobar Menu system Project : Menu
The function to load them into the tab control:
private void LaunchWPFApplication(string header, string pPath)
{
// Header - What loads in the tabs header portion.
// pPath - Page where to send the user
//Create a new browser tab object
BrowserTab bt = tabMain.SelectedItem as BrowserTab;
bt = new BrowserTab();
bt.txtHeader.Text = header;
bt.myParent = BrowserTabs;
//Load in the path
try
{
Type formType = Type.GetType(pPath, true);
bt.Content = (UserControl)Activator.CreateInstance(formType);
}
catch
{
MessageBox.Show("The specified user control : " + pPath + " cannot be found");
}
//Add the browser tab and then focus
BrowserTabs.Add(bt);
bt.IsSelected = true;
}
And what I send to the function as an example:
LaunchWPFApplication("Calculater", "foobar.AppCalculater");
But every time run, the application complains that the formType is null. I am confused on how to load the user control and curious if I'm sending the correct parameters.
Upvotes: 1
Views: 1734
Reputation: 2381
The problem I had was in calling the Type.GetType. The generic call which the MSDN gives is
Type formType = Type.GetType("AppCalculater");
which calls get the type of the specified name. This would still no matter what return a null. I then added the namespace to the mix.
Type formType = Type.GetType("foobar.AppCalculater");
This however was still giving me an error calling the other project files in foobar. To get the user controls in the other project, I added the assembly after the control and namespace call.
Type formType = Type.GetType("foobar.AppCalculater,foobar");
I then was able to reference all the user controls dynamically using this call. Thus my now updated call to load a user control from another project into my tab control is as follows :
private void LaunchWPFApplication(string header, string pPath)
{
// Header - What loads in the tabs top portion.
// Path - Page where to send the user
//Create a new browser tab object
BrowserTab bt = tabMain.SelectedItem as BrowserTab;
bt = new BrowserTab();
bt.txtHeader.Text = header;
bt.myParent = BrowserTabs;
//Load in the path
try
{
Type formType = Type.GetType(pPath); //Example "foobar.foobarUserControl,foobar"
bt.Content = Activator.CreateInstance(formType);
}
catch (ArgumentNullException)
{
MessageBox.Show("The specified user control : " + pPath + " cannot be found");
}
catch (Exception ex)
{
MessageBox.Show("An error has occurred while loaded the specified user control : " + pPath + ". It includes the following message : \n" + ex);
}
//Add the browser tab and then focus
try
{
BrowserTabs.Add(bt);
}
catch(InvalidOperationException)
{
MessageBox.Show("Cannot add " + pPath + " into the tab control");
}
bt.IsSelected = true;
}
Upvotes: 1