Architect's Log

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

Applicationオブジェクトのプロパティで状態を管理する

Applicationオブジェクトはアプリケーションのライフタイム全体で使用可能なので、プロパティで状態管理することも可能です。

ソースコード

App.xaml
<Application x:Class="WpfApplication3.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
</Application>
App.xaml.cs
using System.Windows;

namespace WpfApplication3 {
    public partial class App : Application {

        public string Msg { get; set; }

        public App() {
            this.Msg = "こんにちは";
        }
    }
}
MainWindow.xaml
<Window x:Class="WpfApplication3.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">
    <TextBox Name="textBox" />
</Window>
MainWindows.xaml.cs
using System.Windows;

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

            this.textBox.Text = ((App) Application.Current).Msg;
        }
    }
}

アプリ実行