Skip to content
David Desmaisons edited this page Sep 29, 2016 · 9 revisions

See complete example at: Example.ChromiumFX.Ko.UI

Given the following ViewModel:

public class Skill
{
	public string Type { get;}
	public string Name { get;}

	public Skill (string name, string skillType)
	{
		Name = name;
		Type = skillType;
	}
}

public class Person: ViewModelBase
{
	private string _Name;
	public string Name
	{
		get { return _Name; }
		set { Set(ref _Name, value, "Name"); }
	}

	private Skill _MainSkill;
	public Skill MainSkill
	{
		get { return _MainSkill; }
		set { Set(ref _MainSkill, value, "MainSkill"); }
	}
	   
	public IList<Skill> Skills { get; private set; }

	public ICommand RemoveSkill { get; private set; }
	
	public Person()
	{
		Skills = new ObservableCollection<Skill>();
		RemoveSkill = new RelayCommand<Skill>(s=> this.Skills.Remove(s));
	}	  
}

Bind to a property:

<span data-bind="text:Name"></span>

Bind to a nested property:

<span data-bind="Skill().Name"></span>

Bind to a Collection:

<div data-bind="foreach: Skills()">
     <div ><span data-bind="text:Type"></span></div >
</div>

Note that you need the parathensis as arrays are mapped to observable value wich value is an obsrevable arrray.

Bind to a Command with custom binding :

<button data-bind="command: $data.RemoveSkill"></button>

By default the comand will be called if CanExceute is true on click with element context as command argument.

Bind to a Command with custom binding :

<button data-bind="command: $data.RemoveSkill"></button>

The comand will be called if CanExcecute is true on click with element context as command argument.

Bind to a Command with custom binding on different event:

<button data-bind="command: $data.RemoveSkill, commandoption: { event:'dblclick'}">
</button>

This will call Execute if CanExecute is true with element context as parameter on button double click.

Special Hook

It is possible to create a register method on the global ko object. This method should take one argument which is the ViewModel. It will called before calling ko.applyBindings, so it can be used to register computed properties.

Example:

ko.register = function (vm) {
   vm.count = ko.computed( function() {
       return this.Skills().length;
   }, vm);
}