Phillip Trelford's Array

POKE 36879,255

Silverlight 4 Calculator Sample in F#

If you have Silverlight 4 installed you should see a calculator sample below coded in F#. The sample originally targeted WPF, only a few modifications were required to run in Silverlight:

  • the view is hosted in a UserControl instead of a Window
  • a C# project is used to launch the UserControl and generate the Silverlight XAP file

The sample demonstrates creating a View in WPF or Silverlight without XAML. The idea is to make things a little easier from F# by implementing a (+) operator overload to attach dependency properties.

The following snippet shows the keypad being constructed by transforming tuples describing the key character and action to buttons:

let keys =
    let grid = new Grid()
    for i = 1 to 4 do
        ColumnDefinition() |> grid.ColumnDefinitions.Add 
        RowDefinition() |> grid.RowDefinitions.Add
    [ 
    ['7',Digit(7);'8',Digit(8);'9',Digit(9);'/',Operator(Divide)]
    ['4',Digit(4);'5',Digit(5);'6',Digit(6);'*',Operator(Multiply)]
    ['1',Digit(1);'2',Digit(2);'3',Digit(3);'-',Operator(Minus)]
    ['0',Digit(0);'.',Dot;'=',Evaluate;'+',Operator(Plus)]
    ]    
    |> List.mapi (fun y ys ->
        ys |> List.mapi (fun x (c,key) ->
            let color =
                match key with
                | Operator(_) | Evaluate -> Colors.Yellow
                | Digit(_) | Dot -> Colors.LightGray                        
            let effect =
                Binding("Operator",
                        Converter=operationEffectConverter,
                        ConverterParameter=key)    
            Button(Content=c,CommandParameter=key,
                Width=40.0,Height=40.0,Margin=Thickness(4.0),
                Background=SolidColorBrush(color)) +                
                Button.CommandBinding(Binding("KeyCommand")) +
                Button.EffectBinding(effect) +
                Grid.Column(x) + Grid.Row(y)                         
        )
    )
    |> List.concat
    |> List.iter (grid.Children.Add >> ignore)
    grid

 

Note: This article is more a thought experiment in trying F# code instead of XAML to describe a View. In many cases XAML with a C#/F# View Model may be the pragmatic choice.

PS There is a very concise WebSharper F# Calculator sample, that generates JavaScript.

SilverlightCalculator.zip (10.09 kb)

Pingbacks and trackbacks (2)+

Comments are closed