I currently have one window designed in WPF and coded in C#. I want one of my buttons to open another window, which I would also like to design in WPF. What is the best way for me to do this? Can I make multiple xaml files and call them from the same .cs class? Or should I just have one xaml file? I tried to add a new window into my xaml but it won't allow me to do that. I want all the code to be in the same C# class.
Asked
Active
Viewed 66 times
2 Answers
1
Yes, you can have multiple XAML files and call them from the same .cs file.
For exemple, let's say you have Window1.xaml
and Window2.xaml
. Window1
is your main window, and the code behind will look like this :
public partial class Window1 : Window
{
public MainWindow()
{
InitializeComponent();
}
}
In Window1
you have a button named btnOpenWindow
. On click, you may do that to open Window2
:
private void btnOpenWindow_Click(object sender, RoutedEventArgs e)
{
var window = new Window2();
window.Show();
}
Then a new Window2
is opened.
However you won't be able to get events or others things coming from Window2
in Window1.xaml.cs
, obviously you will control that in Window2.xaml.cs
for exemple.

Chostakovitch
- 965
- 1
- 9
- 33
-1
You should use the MVVM pattern in your project. So you have different windows and just one ViewModel to handel these views and your data.
Have a look on: MVVM: Tutorial from start to finish?