Teil 2: Vollständiger Code (Windows Store-Apps mit C#/VB und XAML)
Inhaltsverzeichnis reduzieren
Inhaltsverzeichnis erweitern

Teil 2: Vollständiger Code (Windows Store-Apps mit C#/VB und XAML)

[ Dieser Artikel richtet sich an Windows 8.x- und Windows Phone 8.x-Entwickler, die Windows-Runtime-Apps schreiben. Wenn Sie für Windows 10 entwickeln, finden Sie weitere Informationen unter neueste Dokumentation ]

Dieses Thema enthält das im Lernprogramm Teil 2: Verwalten von App-Lebenszyklus und -Zustand verwendete vollständige Codebeispiel.

Wichtig  Dieses Lernprogramm ist für Microsoft Visual Studio 2013 und Windows 8.1 konzipiert. Teile des Lernprogramms funktionieren in Verbindung mit Microsoft Visual Studio 2012 und Windows 8 nicht ordnungsgemäß.

Dieses Thema enthält die folgenden Abschnitte:


Dieses Beispiel kann nicht heruntergeladen werden.


ProgrammiersprachenC#, Visual Basic .NET
ProgrammiermodelleWindows Runtime


Unterstützte Mindestversion (Client)Windows 8.1
Unterstützte Mindestversion (Server)Windows Server 2012 R2
Mindestens erforderliches SDKMicrosoft Visual Studio Express 2012 für Windows 8

Anzeigen des Codes (XAML)


App.xaml enthält nur generierten Code.


using System;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

// The Blank Application template is documented at http://go.microsoft.com/fwlink/p/?LinkID=234227

namespace HelloWorld
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    sealed partial class App : Application
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
            this.Suspending += OnSuspending;

        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected async override void OnLaunched(LaunchActivatedEventArgs e)

            if (System.Diagnostics.Debugger.IsAttached)
                this.DebugSettings.EnableFrameRateCounter = true;

            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();
                HelloWorld.Common.SuspensionManager.RegisterFrame(rootFrame, "appFrame");

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                    //TODO: Load state from previously suspended application
                    await HelloWorld.Common.SuspensionManager.RestoreAsync();

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;

            if (rootFrame.Content == null)
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                if (!rootFrame.Navigate(typeof(MainPage), e.Arguments))
                    throw new Exception("Failed to create initial page");
            // Ensure the current window is active

        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        private async void OnSuspending(object sender, SuspendingEventArgs e)
            var deferral = e.SuspendingOperation.GetDeferral();
            //TODO: Save application state and stop any background activity
            await HelloWorld.Common.SuspensionManager.SaveAsync();


    DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"

        <common:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
        <!-- TODO: Delete this line if the key AppName is declared in App.xaml -->
        <x:String x:Key="AppName">Hello, world!</x:String>
        <Style x:Key="BigGreenTextStyle" TargetType="TextBlock">
            <Setter Property="Foreground" Value="Green"/>
            <Setter Property="FontSize" Value="36"/>
            <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/>
            <Setter Property="TextTrimming" Value="CharacterEllipsis"/>
            <Setter Property="TextWrapping" Value="Wrap"/>
            <Setter Property="Typography.StylisticSet20" Value="True"/>
            <Setter Property="Typography.DiscretionaryLigatures" Value="True"/>
            <Setter Property="Typography.CaseSensitiveForms" Value="True"/>
            <Setter Property="LineStackingStrategy" Value="BlockLineHeight"/>
            <Setter Property="TextLineBounds" Value="TrimToBaseline"/>
            <Setter Property="OpticalMarginAlignment" Value="TrimSideBearings"/>

        This grid acts as a root panel for the page that defines two rows:
        * Row 0 contains the back button and page title
        * Row 1 contains the rest of the page layout
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
            <RowDefinition Height="140"/>
            <RowDefinition Height="*"/>

        <!-- Back button and page title -->
                <ColumnDefinition Width="120"/>
                <ColumnDefinition Width="*"/>
            <AppBarButton x:Name="backButton" Icon="Back" Height="95" Margin="10,46,10,0"
                          Command="{Binding NavigationHelper.GoBackCommand, ElementName=pageRoot}" 
                          Visibility="{Binding IsEnabled, Converter={StaticResource BooleanToVisibilityConverter}, RelativeSource={RelativeSource Mode=Self}}"
                          AutomationProperties.ItemType="Navigation Button"/>
            <TextBlock x:Name="pageTitle" Text="{StaticResource AppName}" 
                       Style="{StaticResource HeaderTextBlockStyle}" Grid.Column="1" 
                       IsHitTestVisible="false" TextWrapping="NoWrap" VerticalAlignment="Bottom" Margin="0,0,30,40"/>

        <StackPanel Grid.Row="1" Margin="120,30,0,0">
            <TextBlock Text="What's your name?" Style="{ThemeResource BaseTextBlockStyle}"/>
            <StackPanel Orientation="Horizontal" Margin="0,20,0,20">
                <TextBox x:Name="nameInput" Width="300" HorizontalAlignment="Left" TextChanged="NameInput_TextChanged"/>
                <Button Content="Say &quot;Hello&quot;" Click="Button_Click"/>
            <TextBlock x:Name="greetingOutput" Style="{StaticResource BigGreenTextStyle}"/>


using HelloWorld.Common;
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/p/?LinkID=234237

namespace HelloWorld
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class MainPage : Page

        private NavigationHelper navigationHelper;
        private ObservableDictionary defaultViewModel = new ObservableDictionary();

        /// <summary>
        /// This can be changed to a strongly typed view model.
        /// </summary>
        public ObservableDictionary DefaultViewModel
            get { return this.defaultViewModel; }

        /// <summary>
        /// NavigationHelper is used on each page to aid in navigation and 
        /// process lifetime management
        /// </summary>
        public NavigationHelper NavigationHelper
            get { return this.navigationHelper; }

        public MainPage()
            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += navigationHelper_LoadState;
            this.navigationHelper.SaveState += navigationHelper_SaveState;

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
            // Restore values stored in session state.
            if (e.PageState != null && e.PageState.ContainsKey("greetingOutputText"))
                greetingOutput.Text = e.PageState["greetingOutputText"].ToString();

            // Restore values stored in app data.
            Windows.Storage.ApplicationDataContainer roamingSettings =
            if (roamingSettings.Values.ContainsKey("userName"))
                nameInput.Text = roamingSettings.Values["userName"].ToString();

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        private void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
            e.PageState["greetingOutputText"] = greetingOutput.Text;


        #region NavigationHelper registration

        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        /// Page specific logic should be placed in event handlers for the  
        /// <see cref="GridCS.Common.NavigationHelper.LoadState"/>
        /// and <see cref="GridCS.Common.NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method 
        /// in addition to page state preserved during an earlier session.

        protected override void OnNavigatedTo(NavigationEventArgs e)

        protected override void OnNavigatedFrom(NavigationEventArgs e)


        private void Button_Click(object sender, RoutedEventArgs e)
            greetingOutput.Text = "Hello, " + nameInput.Text + "!";

        private void NameInput_TextChanged(object sender, TextChangedEventArgs e)
            Windows.Storage.ApplicationDataContainer roamingSettings =
            roamingSettings.Values["userName"] = nameInput.Text;



© 2016 Microsoft