How do I open a second window from the first window in WPF?

前端 未结 9 1201
一个人的身影
一个人的身影 2020-11-29 20:46

I am new to WPF. I have two windows, such as window1 and window2. I have one button in window1. If I click that button, the window2 has to open. What should I do for that?

相关标签:
9条回答
  • 2020-11-29 21:19

    You can create a button in window1 and double click on it. It will create a new click handler, where inside you can write something like this:

    var window2 = new Window2();
    window2.Show();
    
    0 讨论(0)
  • 2020-11-29 21:23

    When you have created a new WPF application you should have a .xaml file and a .cs file. These represent your main window. Create an additional .xaml file and .cs file to represent your sub window.

    MainWindow.xaml

    <Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
        <Grid>
            <Button Content="Open Window" Click="ButtonClicked" Height="25" HorizontalAlignment="Left" Margin="379,264,0,0" Name="button1" VerticalAlignment="Top" Width="100" />
        </Grid>
    </Window>
    

    MainWindow.xaml.cs

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    
        private void ButtonClicked(object sender, RoutedEventArgs e)
        {
            SubWindow subWindow = new SubWindow();
            subWindow.Show();
        }
    }
    

    Then add whatever additional code you need to these classes:

    SubWindow.xaml
    SubWindow.xaml.cs
    
    0 讨论(0)
  • 2020-11-29 21:25

    This helped me: The Owner method basically ties the window to another window in case you want extra windows with the same ones.

    LoadingScreen lc = new LoadingScreen();
    lc.Owner = this;
    lc.Show();
    

    Consider this as well.

    this.WindowState = WindowState.Normal;
    this.Activate();
    
    0 讨论(0)
提交回复
热议问题