using System;
using System.Collections.Generic;
using System.Text;
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.Shapes;
using System.Windows.Navigation;
using System.ComponentModel;

namespace PageState {
  public partial class Page1 : Page {

    class GameData : INotifyPropertyChanged {
      int guess = 452;
      public int Guess {
        get { return guess; }
        set { guess = value; Notify("Guess"); }
      }

      int answer = (new Random()).Next();
      public int Answer {
        get { return answer; }
        set { answer = value; Notify("Answer"); }
      }

      // INotifyPropertyChanged Members
      public event PropertyChangedEventHandler PropertyChanged;
      void Notify(string prop) { if( PropertyChanged != null ) { PropertyChanged(this, new PropertyChangedEventArgs(prop)); } }
    }

    GameData guess = new GameData();

    public Page1() {
      InitializeComponent();
      DataContext = guess;
      Loaded += new RoutedEventHandler(Page1_Loaded);
      Unloaded += new RoutedEventHandler(Page1_Unloaded);
    }

    void NavigationService_Navigating(object sender, NavigatingCancelEventArgs e) {
      if( e.NavigationMode == NavigationMode.New ) {
        if( MessageBox.Show("Allow navigation?", "?", MessageBoxButton.YesNo) == MessageBoxResult.No ) {
          e.Cancel = true;
        }
        else {
          NavigationService.Navigating -= NavigationService_Navigating;
        }
      }
    }

    void Page1_Loaded(object sender, RoutedEventArgs e) {
      Window parent = Parent as Window;
      if( parent != null ) { parent.Width = 400; parent.Height = 200; }
      NavigationService.Navigating += NavigationService_Navigating;
    }

    void Page1_Unloaded(object sender, RoutedEventArgs e) {
      MessageBox.Show("You guessed: " + guess.Guess);
    }

  }

  public class PositiveInteger : ValidationRule {
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) {
      int x;
      if( int.TryParse((string)value, out x) ) return ValidationResult.ValidResult;
      return new ValidationResult(false, "Please enter a number between 0 and 2147483647");
    }
  }

}