Skip to content

Instantly share code, notes, and snippets.

@kimsk
Created November 16, 2013 05:03
Show Gist options
  • Save kimsk/7496177 to your computer and use it in GitHub Desktop.
Save kimsk/7496177 to your computer and use it in GitHub Desktop.
Creating ViewModel for WinRT app in F#.
<Page
x:Class="Win8App.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Win8App"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:fSharpVm="using:FSharpVm"
mc:Ignorable="d">
<Page.Resources>
<fSharpVm:MainPageViewModel x:Key="MainPageViewModel"/>
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center"
DataContext="{StaticResource MainPageViewModel}">
<TextBlock Text="{Binding Count}"
FontSize="72"
HorizontalAlignment="Center">0</TextBlock>
<StackPanel Orientation="Horizontal">
<Button Command="{Binding Increase}">Increase</Button>
<Button Command="{Binding Decrease}">Decrease</Button>
</StackPanel>
</StackPanel>
</Grid>
</Page>
namespace FSharpVm
type MainPageViewModel() =
inherit ViewModelBase()
let mutable _count = 0
member x.Count
with get() = _count
and set count =
_count <- count
x.OnPropertyChanged "Count"
member x.Increase =
new RelayCommand ((fun canExecute -> true),
(fun action -> x.Count <- x.Count + 1))
member x.Decrease =
new RelayCommand ((fun canExecute -> true),
(fun action -> x.Count <- x.Count - 1))
namespace FSharpVm
open System
open System.Windows.Input
open System.ComponentModel
// from F# Windows App (WPF, MVVM) template by Daniel Mohl
// http://visualstudiogallery.msdn.microsoft.com/ad49fd5c-930c-4fe6-a30e-2d0d6778c565?SRC=VSIDE
type RelayCommand (canExecute:(obj -> bool), action:(obj -> unit)) =
let event = new DelegateEvent<EventHandler>()
interface ICommand with
[<CLIEvent>]
member x.CanExecuteChanged = event.Publish
member x.CanExecute arg = canExecute(arg)
member x.Execute arg = action(arg)
namespace FSharpVm
open System.ComponentModel
// from F# Windows App (WPF, MVVM) template by Daniel Mohl
// http://visualstudiogallery.msdn.microsoft.com/ad49fd5c-930c-4fe6-a30e-2d0d6778c565?SRC=VSIDE
type ViewModelBase() =
let propertyChangedEvent = new DelegateEvent<PropertyChangedEventHandler>()
interface INotifyPropertyChanged with
[<CLIEvent>]
member x.PropertyChanged = propertyChangedEvent.Publish
member x.OnPropertyChanged propertyName =
propertyChangedEvent.Trigger([| x; new PropertyChangedEventArgs(propertyName) |])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment