動作環境
Windows 7 Pro (32bit)
Microsoft Visual Studio 2017 Community
Sublime Text 2
C++ Builderで頻繁に使う「2つのフォームがあり、片方のフォームからもう片方のフォームを開く」ということをVS/WPFではどのように行うか。
それをしているのが下記のビデオ。
youtube動画: Open new window from another window in WPF - Part - 10
手順
- ソリューションエクスプローラでウィンドウを追加
- 右クリック
- 追加(D)
- ウィンドウ(I)
- ウィンドウ(WPF)、を選択
- 名前(例): Window2.xaml
- 元のウィンドウ(MainWindow)のコード > Button押下イベント
- Window2のインスタンスを生成
- Show()を実行
- this.Close()
- MainWindowを閉じたい場合
コード
MainWindow
MainWindow.xaml
<Window x:Class="_170430_t0655_openWindow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:_170430_t0655_openWindow"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel>
<TextBlock Text="1st"/>
<Button x:Name="B_open" Content="Open" Click="B_open_Click"/>
</StackPanel>
</Grid>
</Window>
MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace _170430_t0655_openWindow
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void B_open_Click(object sender, RoutedEventArgs e)
{
Window2 awin2 = new Window2();
awin2.Show();
this.Close();
}
}
}
Window2
Window2.xaml
<Window x:Class="_170430_t0655_openWindow.Window2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:_170430_t0655_openWindow"
mc:Ignorable="d"
Title="Window2" Height="300" Width="300">
<Grid>
<TextBlock Text="2nd"/>
</Grid>
</Window>
実行例
MainWindowのボタンを押すと、Window2(下記)が開く。MainWindowは閉じる。
C++ Builder XE4との違い
- アプリ実行時のフォーム自動生成はどうする?
- 今のところどのようにするか不明
- Window2に関するincludeをせずとも、Window2のインスタンスを生成できる
- C#による違いなのかも