Architect's Log

I'm a Cloud Architect. I'm highly motivated to reduce toils with driving DevOps.

Application.Propertiesを使用してページ間で状態を受け渡す

アプリ実行

Application.Propertiesを使用して、入力された名前を次のページに受け渡します。

Page1.xaml


BloodType.xaml


ソースコード

App.xaml
<Application x:Class="HelloWorld.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="Page1.xaml">
</Application>
Page1.xaml
<Page x:Class="HelloWorld.Page1"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"
    WindowTitle="あなたはの血液型は?">
    <StackPanel>
        <Label>あなたはの血液型は?</Label>
        <TextBox Name="bloodTypeTextBox"></TextBox>
        <TextBlock>
            <Hyperlink 
                NavigateUri="BloodType.xaml"
                RequestNavigate="Hyperlink_RequestNavigate">
                送信
            </Hyperlink>
        </TextBlock>
    </StackPanel>
</Page>
Page1.xaml.cs
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;

namespace HelloWorld {
    public partial class Page1 : Page {
        public Page1() {
            InitializeComponent();
        }

        private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e) {
            // Application.Propertiesに設定しておく。
            Application.Current.Properties["BloodType"] = this.bloodTypeTextBox.Text;
        }
    }
}
BloodType.xaml
<Page x:Class="HelloWorld.BloodType"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"
    Loaded="Page_Loaded">
    <StackPanel>
        <TextBlock>あなたの血液型は、</TextBlock>
        <Label Name="bloodTypeLabel"></Label>
        <TextBlock>型ですね。</TextBlock>
    </StackPanel>
</Page>
BloodType.xaml.cs
using System.Windows;
using System.Windows.Controls;

namespace HelloWorld {
    public partial class BloodType : Page {
        public BloodType() {
            InitializeComponent();
        }

        private void Page_Loaded(object sender, RoutedEventArgs e) {
            // Application.Propertiesから受け取る。
            this.bloodTypeLabel.Content = Application.Current.Properties["BloodType"];
        }
    }
}