I created a UserControl that contains a textbox. When I try to initialize the textbox in the constructor of the UserControl, with some text like this
public FileSelector()
{
InitializeComponent();
TB_FolderPath.Text = @"c:\tmp\Test\";
}
I get an error in the MainWindow.xaml
Cannot create an instance of “FileSelector”.
When I remove the row
TB_FolderPath.Text = @"c:\tmp\Test\";
I don’t get the error, but of course an empty textbox.
Previously when I had the parts of the UserControl integrated in the MainWindow, there was also no problem.
I tried to create a simpler version of MainWindow using a UserControl to reproduce the problem, but in a simple case it works.
So, my questions.
-
What can be the cause of the problem?
-
How can I debug/analyze a problem like this systematically? I just get the this error in VisualStudio after building, without an explanation.
-
How/Where can I initialize the controls in a
UserControl. In general, is theUserControlthe right place to initialize the controls or would theMainWindowbe also a possibility? (Is this possible at all?)
In WPF, unlike WinForms, the controls are not initialized completely after InitializeComponent(). Hence the uninitialized/unloaded controls throw errors.
You need to write handler to capture the Loaded event of the control.
Read Object Lifetime Events.
Get some more detailed info here.
Example (partially taken from OP’s code):