Skip to content
Marek Linka edited this page Jul 23, 2016 · 4 revisions

Getting started with WFBind

Project preparation

  1. Clone the repository and build the library from source
  2. Reference the library from your project in Visual Studio

Creating a viewmodel

  1. Create a new class in your project, e.g. MyViewModel
  2. Decorate your class with the INotifyPropertyChanged interface located in the System.ComponentModel namespace
  3. Implement the interface (or let Visual Studio do it for you)
  4. Add a read/write property to your viewmodel, e.g. Greeting of type string (note the OnPropertyChanged() call):
public string Greeting
{
    get { return _greeting; }
    get
    { 
        _greeting = value;
        OnPropertyChanged();
    }
}

Set the default value for the _greeting field to whatever you like, e.g. Hello, world!.

Binding a label to the viewmodel

  1. Create or open a Form in your project
  2. Add a new Label to the form and name it GreetingLabel
  3. Open the code-behind file for the form and add the following code to the form's constructor
_myViewModel = new MyViewModel();
BindingManager.Bind(this).To(_myViewModel);
BindingManager.For(this).Bind(GreetingLabel, _ => _.Text).To(_myViewModel, vm => vm.Greeting);

Run the application and open the form. The label will automatically display the text Hello, world!. And that's it, you just created your first databinding using WFBind!

The binding automatically reacts to changes in the viewmodel, so if you add a button to your form that changes the Greeting property, the label will reflect the change:

private void button1_Click(object sender, EventArgs e)
{
    _myViewModel.Greeting = "WFBind works!";
}

Setting up bindings always works the same way, using the same syntax. For example, to set a two-way binding for a text box that only updates when the textbox loses focus, you would use the following syntax:

BindingManager.For(this)
              .Bind(textBox1, _ => _.Text)
              .To(_myViewModel, _ => _.Greeting)
              .Setup(_ => _.IsTwoWay = true)
              .Setup(_ => _.UpdateSourceTrigger = UpdateSourceType.LostFocus);

To bind a viewmodel command to a button, first create a command - it needs to implement the WFBind.ICommand interface. Then add a property to the viewmodel, e.g. MyCommand. Bind it to a button on the form using the following syntax:

BindingManager.For(this).BindCommand(MyButton).To(_myViewModel, _ => _.MyCommand)

There are various types of binding support in WFBind, with still more to come as the code base matures. You will also notice that everything is fully strongly-typed to help prevent certain kind of mistakes in binding setup.

Clone this wiki locally