WP7 to Win8 - reflectionit.nl ·
Transcript of WP7 to Win8 - reflectionit.nl ·
• Visual C#
ASP.NET WebForms & MVC, Silverlight, Windows Phone, Windows 8
• SQL Server
• Trainer
www.reflectionit.nl
View (XAML UserControls + CodeBehind)
ViewModel(State + Operations)
DataBinding Commands Events / Messages
Model(“Data”)
DataBinding
public class MainViewModel : ViewModelBase {
private Question _question = new Question();
public ICommand GenerateCommand { get; set; }
public ICommand AnswerCommand { get; set; }
public MainViewModel() {
this.GenerateCommand = new RelayCommand(() => this.Question = new Question());
this.AnswerCommand = new RelayCommand<Answer>(OnAnswer);
}
public Question Question {
get { return _question; }
set {
if (_question != value) {
_question = value;
RaisePropertyChanged("Question");
}
}
}
private void OnAnswer(Answer a) {
a.Status = a.IsCorrect ? AnswerStatus.Correct : AnswerStatus.Incorrect;
}
}
<Grid x:Name="ContentPanel“
DataContext="{StaticResource MainViewModelDataSource}">
<Grid.RowDefinitions>...</Grid.RowDefinitions>
<TextBlock HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="{StaticResource FontSize}"
Text="{Binding Question.Text}" />
<ItemsControl Grid.Row="1"
ItemsSource="{Binding Question.Answers}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:AnswerButton />
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<toolkit:WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
<Button Content="Generate"
Grid.Row="2"
FontSize="48"
Command="{Binding GenerateCommand}" />
</Grid>
<UserControl xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation"
...
x:Class="Flashcard.AnswerButton"
Width="227"
Height="227">
<i:Interaction.Behaviors>
<ReflectionIT_Phone_Behaviors:EnumDataStateBehavior Binding="{Binding Status}" />
</i:Interaction.Behaviors>
<Grid x:Name="LayoutRoot"
Background="Transparent">
<VisualStateManager.VisualStateGroups>
...
</VisualStateManager.VisualStateGroups>
<Button x:Name="button"
FontSize="{StaticResource FontSize}"
Content="{Binding Text}"
Command="{Binding AnswerCommand, Source={StaticResource MainViewModelDataSource}}"
CommandParameter="{Binding}"
Background="#FD000000">
</Button>
</Grid>
</UserControl>
public class EnumDataStateBehavior : Behavior<Control> {
private object StateValue { get; set; }
protected override void OnAttached() {
base.OnAttached();
this.AssociatedObject.Loaded += new RoutedEventHandler(AssociatedObject_Loaded);
}
private void AssociatedObject_Loaded(object sender, RoutedEventArgs e) {
UpdateVisualState();
}
private void UpdateVisualState() {
if (this.AssociatedObject != null && StateValue != null) {
VisualStateManager.GoToState(this.AssociatedObject, StateValue.ToString(), this.UseTransitions);
}
}
private static void OnBindingPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
var source = d as EnumDataStateBehavior;
if (source != null) {
source.StateValue = e.NewValue;
source.UpdateVisualState();
}
}
<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:vm="using:Flashcard.ViewModels"x:Class="Flashcard.App">
<Application.Resources><!--<vm:MainViewModel x:Key="MainViewModelDataSource" />--><x:Double x:Key="FontSize">100</x:Double>
</Application.Resources></Application>
protected override void OnLaunched(LaunchActivatedEventArgs args) {App.Current.Resources["MainViewModelDataSource"] = new MainViewModel();Window.Current.Content = new Views.MainPage();Window.Current.Activate();
}
<toolkit:WrapPanel /> <WrapGrid />
clr-namespace: using:
xmlns:local="using:Flashcard.Views"
<ResourceDictionary Source="R"R"R"Resources/ThemeResources.xaml" />
public class GoToStateServices {
#region Binding Attached Property
/// <summary>
/// Identifies the Binding attachted property. This enables animation, styling, binding, etc...
/// </summary>
public static readonly DependencyProperty BindingProperty =
DependencyProperty.RegisterAttached("Binding",
"Object",
typeof(GoToStateServices).FullName,
new PropertyMetadata(null, OnBindingChanged));
/// <summary>
/// Binding changed handler.
/// </summary>
/// <param name="d">FrameworkElement that changed its Binding attached property.</param>
/// <param name="e">DependencyPropertyChangedEventArgs with the new and old value.</param>
private static void OnBindingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
var source = d as Control;
if (source != null) {
var value = e.NewValue;
value = Enum.ToObject(Type.GetType(GoToStateServices.GetBindingType(source).ToString()), value);
VisualStateManager.GoToState(source, value.ToString(), true);
}
}
<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:vm="using:Flashcard.ViewModels"x:Class="Flashcard.App">
<Application.Resources>
<ResourceDictionary><ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources/ThemeResources.xaml" />
<!--http://code.msdn.microsoft.com/windowsapps/Light-and-Dark-Theme-Xaml-eca02f2b --><ResourceDictionary Source="Resources/Generic.xaml" />
</ResourceDictionary.MergedDictionaries>
<!--<vm:MainViewModel x:Key="MainViewModelDataSource" />--><x:Double x:Key="FontSize">100</x:Double>
</ResourceDictionary>
</Application.Resources>
</Application>
http://blogs.msdn.com/b/avip/archive/2011/09/18/windows-8-development-tidbits-observablecollection-doesn-t-work.aspx
http://code.msdn.microsoft.com/windowsapps/Data-Binding-7b1d67b5
http://www.scottlogic.co.uk/blog/colin/2011/10/using-observablecollection-with-winrt-via-a-little-shim/
http://blogs.u2u.be/diederik/post/2012/01/03/Hello-ObservableVector-goodbye-ObservableCollection.aspx
<WrapGrid >
<WrapGrid.ChildrenTransitions>
<TransitionCollection>
<EntranceThemeTransition FromHorizontalOffset="100" />
</TransitionCollection>
</WrapGrid.ChildrenTransitions>
</WrapGrid>
private void Button1_Click(object sender, RoutedEventArgs e) {
var result = MessageBox.Show("This is MessageBox", "Title", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK) {
// do something
}
Button1.Content = result.ToString();
}
private async void Button1_Click(object sender, RoutedEventArgs e) {
MessageDialog md = new MessageDialog("This is a MessageDialog", "Title");
bool? result = null;
md.Commands.Add(new UICommand("OK", new UICommandInvokedHandler((cmd) => result = true)));
md.Commands.Add(new UICommand("Cancel", new UICommandInvokedHandler((cmd) => result = false)));
await md.ShowAsync();
if (result == true) {
// do something
}
Button1.Content = result.ToString();
}
class MessageBox {
public static async Task<MessageBoxResult> ShowAsync(string messageBoxText, string caption, MessageBoxButton button) {
MessageDialog md = new MessageDialog(messageBoxText, caption);
MessageBoxResult result = MessageBoxResult.None;
md.Commands.Add(new UICommand("OK", new UICommandInvokedHandler((cmd) => result = MessageBoxResult.OK)));
if (button == MessageBoxButton.OKCancel) {
md.Commands.Add(new UICommand("Cancel", new UICommandInvokedHandler((cmd) => result = MessageBoxResult.Cancel)));
}
var op = await md.ShowAsync();
return result;
}
public static async Task<MessageBoxResult> ShowAsync(string messageBoxText) {
return await MessageBox.ShowAsync(messageBoxText, null, MessageBoxButton.OK);
}
}
public enum MessageBoxButton {
OK = 0, OKCancel = 1,
}
public enum MessageBoxResult {
None = 0, OK = 1, Cancel = 2,
}
private void Button1_Click(object sender, RoutedEventArgs e) {
var result = MessageBox.Show("This is MessageBox", "Title", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK) {
// do something
}
Button1.Content = result.ToString();
}
private async void Button1_Click(object sender, RoutedEventArgs e) {
var result = await MessageBox.ShowAsync("This is MessageBox", "Title", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK) {
// do something
}
Button1.Content = result.ToString();
}
private void Application_Launching(object sender, LaunchingEventArgs e) { RestoreSettings(); }
private void Application_Activated(object sender, ActivatedEventArgs e) {
if (!e.IsApplicationInstancePreserved) RestoreSettings();
}
private void Application_Deactivated(object sender, DeactivatedEventArgs e) { SaveSettings(); }
private void Application_Closing(object sender, ClosingEventArgs e) { SaveSettings(); }
private void RestoreSettings() {
object value;
if (IsolatedStorageSettings.ApplicationSettings.TryGetValue("Question", out value)) {
this.ViewModel.Question = value as Models.Question;
}
}
private void SaveSettings() {
IsolatedStorageSettings.ApplicationSettings["Question"] = this.ViewModel.Question;
}
private MainViewModel ViewModel {
get { return this.Resources["MainViewModelDataSource"] as MainViewModel; }
}
protected async override void OnLaunched(LaunchActivatedEventArgs args) {
App.Current.Resources["MainViewModelDataSource"] = new MainViewModel();
if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) {
await this.RestoreSettings();
}
this.Suspending += App_Suspending;
this.Resuming += App_Resuming;
this.Exiting += App_Exiting;
Window.Current.Content = new Views.MainPage();
Window.Current.Activate();
}
private async void App_Resuming(object sender, object e) {
await RestoreSettings();
}
private async Task RestoreSettings() {
await SuspensionManager.RestoreAsync();
object value;
if (SuspensionManager.SessionState.TryGetValue("Question", out value)) {
this.ViewModel.Question = value as Models.Question;
}
}
private async void App_Exiting(object sender, object e) {
await SaveSettings();
}
private async void App_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e) {
await SaveSettings();
e.SuspendingOperation.GetDeferral().Complete();
}
private async Task SaveSettings() {
SuspensionManager.SessionState["Question"] = this.ViewModel.Question;
await SuspensionManager.SaveAsync();
}
private MainViewModel ViewModel {
get { return this.Resources["MainViewModelDataSource"] as MainViewModel; }
}
<TextBlock x:Name="ApplicationTitle"
Style="{StaticResource PhoneTextNormalStyle}"
x:Uid="TextBlockTitle"
Text="FLASHCARD" />
private void Page_LayoutChanged(object sender, ApplicationLayoutChangedEventArgs e) {
SetCurrentViewState(this);
}
private void Page_OrientationChanged(object sender) {
SetCurrentViewState(this);
}
private void SetCurrentViewState(Control viewStateAwareControl) {
VisualStateManager.GoToState(viewStateAwareControl, this.GetViewState(), false);
}
private String GetViewState() {
var orientation = DisplayProperties.CurrentOrientation;
if (orientation == DisplayOrientations.Portrait ||
orientation == DisplayOrientations.PortraitFlipped) return "Portrait";
var layout = ApplicationLayout.Value;
if (layout == ApplicationLayoutState.Filled) return "Fill";
if (layout == ApplicationLayoutState.Snapped) return "Snapped";
return "Full";
}
http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/8539a645-e84f-4669-87a7-20e3731322a7