Search
Project Description
An Imperative Reactive Programming library for F#.

Your questions, comments, ideas and code contributions are welcome.

Example

In this example we create a GUI that looks like this:

[ textboxA ] + [ textboxB ] = [ textboxC ]

Initially the contents are 3, 4 and 7:

[ 3 ] + [ 4 ] = [ 7 ]

The program will update the other textboxes when you edit one of the textboxes. So if you change the 4 to a 5 you get this:

[ 3 ] + [ 5 ] = [ 8 ]

Notice that the program updated the 7 to an 8.

First we set up the window with controls:

let w = new Window()
let p = new WrapPanel()
w.Content <- p
let textboxA = new TextBox(Text="3")
let plus = new TextBlock(Text=" + ")
let textboxB = new TextBox(Text="4")
let equals = new TextBlock(Text=" = ")
let textboxC = new TextBox()
p.Children.Add(textboxA)
p.Children.Add(plus)
p.Children.Add(textboxB)
p.Children.Add(equals)
p.Children.Add(textboxC)
w.Show()


Because the textboxes contain strings we need a function to convert them to integers:

let parse s = match int.TryParse(s) with 
                | (true,n) -> n
                | (false,_) -> 0


Now we're set up and can start using the library.
A Cell<'t> is a time varying value. You can think of a cell as an observable reference.

We can get cells representing the text property of the textboxes like this:

let cellA = property textboxA TextBox.TextProperty
let cellB = property textboxB TextBox.TextProperty
let cellC = property textboxC TextBox.TextProperty


The type of these is Cell<string>. To sum cellA+cellB we have to use the cell builder:

let sumAB = cell {
        let! a = cellA // extract the contents
        let! b = cellB
        return string (parse a + parse b)
      }


This code will be executed every time cellA or cellB changes. You can verify this:

let sumAB = cell {
        let! a = cellA // extract the contents
        let! b = cellB
        do printf "cellA or cellB updated"
        return string (parse a + parse b)
      }


If you put the printf one line higher it will only execute when cellA updates:

let sumAB = cell {
        let! a = cellA // extract the contents
        do printf "cellA updated"
        let! b = cellB
        return string (parse a + parse b)
      }


Now we bind the text property of textboxC to this sum:

cellC .= sumAB


The GUI updates textboxC if you change textboxA or textboxB, but not the other way around. If you manually edit textboxC you can end up with an incorrect equation:

[ 3 ] + [ 4] = [ 8 ]

Exercise

Make sure that the program also update both ways, i.e. updates textboxB when you change textboxC. You can do this by binding cellB to the difference of cellC and cellA.
Last edited Jul 28 2009 at 2:35 PM by JulesJacobs, version 14
Updating...
© 2006-2012 Microsoft | Get Help | Privacy Statement | Terms of Use | Code of Conduct | Advertise With Us | Version 2012.2.15.18416