I think you're correct that the TextBox
on the first form no longer exists, which is why you're getting the error. This is because WPF unloads controls that are no longer visible, and all data from them is forgotten unless they're bound to something in the DataContext.
I would highly recommend using the MVVM design pattern if you're working with WPF. It's perfectly suited to the technology, and I find it keeps the code clean and easy to maintain.
In your situation, I would have a single ViewModel
for your entire application, and have it contain the SubmitCommand
and 5 data objects, each representing the data from one "Form"
For example, your MainViewModel might look like this:
public MainViewModel : INotifyPropertyChanged
{
// Should be full properties that implement INotifyPropertyChanged,
// but leaving that out for simplicity right now
public ObservableCollection<object> Forms { get; set; }
public object CurrentForm { get; set; }
public ICommand SubmitCommand { get; set; }
// Could also add ICommands for Back and Next buttons as well
public MainViewModel()
{
Forms = new ObservableCollection()
{
new Form1Data(),
new Form2Data(),
new Form3Data(),
new Form4Data(),
new Form5Data()
};
CurrentForm = Forms.FirstOrDefault();
}
}
And your XAML would look something like this:
<Window>
<Window.Resources>
<DataTemplate DataType="{x:Type local:Form1Data}">
<local:Form1UserControl />
</DataTemplate>
<DataTemplate DataType="{x:Type local:Form2Data}">
<local:Form2UserControl />
</DataTemplate>
<DataTemplate DataType="{x:Type local:Form3Data}">
<local:Form3UserControl />
</DataTemplate>
<DataTemplate DataType="{x:Type local:Form4Data}">
<local:Form4UserControl />
</DataTemplate>
<DataTemplate DataType="{x:Type local:Form5Data}">
<local:Form5UserControl />
</DataTemplate>
</Window.Resources>
<DockPanel>
<Button Command="{Binding SubmitCommand}"
Content="Submit" DockPanel.Dock="Bottom" />
<ContentControl Content="{Binding CurrentForm}" />
</DockPanel>
</Window>
(You could also write out form controls in XAML in the DataTemplates instead of using a UserControl)
If you're new to WPF and the MVVM design pattern, I have a very simple example on my blog that you may be interested in reading to get started.
Edit
I just saw your updated question with the code, and your problem here is that you have two copies of your SendMail
class, one with your first window and one with your second window. You need to have a single copy of the SendMail
class, and have it reference both windows.
Although like I said in the beginning of my answer, I don't think that will work because WPF unloads UI objects that aren't visible, so it's likely that any data in your Window will be lost when you .Close()
it.