How to open another window in WPF using C#?

In WPF, to open another window, you can create a new window instance using the Window class and display it using the Show() method.

Here is a sample code demonstrating how to open another window from a WPF window.

// MainWindow.xaml.cs

using System.Windows;

namespace YourNamespace
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void OpenNewWindowButton_Click(object sender, RoutedEventArgs e)
        {
            NewWindow newWindow = new NewWindow(); // 创建新窗口实例
            newWindow.Show(); // 显示新窗口
        }
    }
}
// NewWindow.xaml.cs

using System.Windows;

namespace YourNamespace
{
    public partial class NewWindow : Window
    {
        public NewWindow()
        {
            InitializeComponent();
        }
    }
}

In the MainWindow.xaml file, include a button that, when clicked, will call the OpenNewWindowButton_Click method to open a new window.

<!-- MainWindow.xaml -->

<Window x:Class="YourNamespace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Main Window" Height="450" Width="800">
    <Grid>
        <Button Content="Open New Window" Click="OpenNewWindowButton_Click" />
    </Grid>
</Window>

In this way, when the button is clicked, a new window will open.

bannerAds