Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

wpf

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?

Here is the code I tried:

window2.show(); 
like image 636
ASHOK A Avatar asked Jun 21 '12 08:06

ASHOK A


People also ask

How do I navigate to another window in WPF?

NavigationService is for browser navigation within WPF. What you are trying to do is change to a different window TrainingFrm . To go to a different window, you should do this: private void conditioningBtn_Click(object sender, RoutedEventArgs e) { var newForm = new TrainingFrm(); //create your new form.

How do I open a WPF window?

Open as modal WPF restricts interaction to the modal window, and the code that opened the window pauses until the window closes. This mechanism provides an easy way for you to prompt the user with data and wait for their response. Once a window is closed, the same object instance can't be used to reopen the window.


2 Answers

Write your code in window1.

private void Button_Click(object sender, RoutedEventArgs e) {     window2 win2 = new window2();     win2.Show(); } 
like image 72
CHANDRA Avatar answered Oct 18 '22 23:10

CHANDRA


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 
like image 25
TokyoMike Avatar answered Oct 18 '22 22:10

TokyoMike