Using slideToggle with Knockout’s MVVM

I recommend you use the third option: Option 3 – Boolean binding using a custom binding handler called slideToggle

See it live here:

<!-- Step 1a - Create the HTML File or the View -->
<!DOCTYPE html>
    <!-- Step 2 - Include jquery and knockout -->
    <script type="text/javascript" src=""></script>
    <script type="text/javascript" src=""></script>
    <!-- Step 3 - Add script to run when page loads -->
    <script type="text/javascript">
            <!-- Step 4 - Create a ViewModel -->           
            function viewModel() {
                _self = this;
                _self.showHideChild = function(viewModel, event) {
                _self.showHideNextSibling = function(viewModel, event) {
                    var siblings = $(event.currentTarget).siblings('div');
                    for (var i=0;i<siblings.length;i++) {
                        if (siblings[i].previousElementSibling == event.currentTarget ) {
                _self.isVisible = ko.observable(false);
                _self.showHide = function() {
            ko.bindingHandlers.slideToggle = {
                init: function (element, valueAccessor) {
                    var value = valueAccessor();
                update: function (element, valueAccessor) {
                    var value = valueAccessor();
                    var isVisible = element.offsetWidth > 0 && element.offsetHeight > 0;
                    if (ko.utils.unwrapObservable(value) != isVisible) {
            <!-- Step 5 -  Activates knockout.js bindings -->
          ko.applyBindings(new viewModel());
<!-- Step 4 - Create a HTML Elements with bindings -->
<body style="">
        Option 1 - Child div
        <div id="child1" data-bind="click: showHideChild" style="border:2px solid;">
        Click me
            <div id="child2" style="display: none;">
              Now you see me!
        Option 2 - Siblings div
        <div id="sib1" style="border:2px solid;">
            <div id="sib2" data-bind="click: showHideNextSibling" >
            Click me
            <div id="sib3" style="display: none;">
            Now you see me!
            <div id="sib4">
            You should always see me.
        Option 3 - Boolean binding using a custom binding handler called slideToggle 
        <div id="bool1" style="border:2px solid;">
            <div id="bool2" data-bind="click: showHide" >
            Click me
            <div id="bool3" data-bind="slideToggle: isVisible">
            Now you see me!

HTML Search using MVVM with knockout.js

<!DOCTYPE html>
    <script type="text/javascript" src=""></script>
    <script type="text/javascript" src=""></script>
    <script type="text/javascript" >
            // custom binding handler so pressing enter in a textbox is the same
            // as clicking the button.
            ko.bindingHandlers.enterKey = {
                init: function(element, valueAccessor, allBindings, vm) {
                    ko.utils.registerEventHandler(element, "keyup", function(event) {
                        if (event.keyCode === 13) {
                            ko.utils.triggerEvent(element, "change");
                            valueAccessor().call(vm, vm);
                        return true;
            var fakeSearch = function(args, callback) {
                var data = args;
                return args;

            var ButtonViewModel = function(text, searchMethod, canSearchMethod) {
                var _self = this;
                _self._canSearchMethod = canSearchMethod;
                _self.text = ko.observable(text);
                _self.onClick = searchMethod;
                _self.canClick = ko.computed(_self._canSearchMethod);                

            var SearchParametersViewModel = {
                'SearchTerm': ko.observable(''),
                'SearchOption': ko.observable(''), // Not used in example
                'StartDate': ko.observable(''),    // Not used in example
                'EndDate': ko.observable('')       // Not used in example

            var SearchViewModel = function(searchMethod, searchArgs) {
                // private properties
                var _self = this;
                _self._searchMethod = searchMethod;
                _self._searchArgs = searchArgs;
                _self._canSearch = function() {
                    return _self.searchParameters.SearchTerm() != null && _self.searchParameters.SearchTerm() != '';

                // public properties
                _self.searchParameters = SearchParametersViewModel;

                _self.results = ko.observable('');
                _self.searchCallBack = function (data) {

                _self.searchButton = new ButtonViewModel("Search", 
                function () {
                    _self._searchMethod(_self._searchArgs, _self.searchCallBack);
                }, _self._canSearch);
          ko.applyBindings(new SearchViewModel(fakeSearch, {a: "1", b: "2"}));
    <input data-bind="value: searchParameters.SearchTerm, valueUpdate: 'afterkeydown', enterKey: searchButton.onClick" />
    <button type="button" id="btnSearch" data-bind="text: searchButton.text, enable: searchButton.canClick, click: searchButton.onClick"></button>
    <p data-bind="text: results"></p>

WPF MVVM Tutorial

Hey all, here is my WPF MVVM knowledge. You should read these articles, whether mine or sites I link to.

However, you may want to skip my stuff and go straight to this nice little training by Karl Shifflett.
In the Box – MVVM Training

  1. A quick overview of MVVM
  2. Binding Visibility to a bool value in WPF
  3. A Hello World template of a WPF application using MVVM
  4. How Do I: Build Data-driven WPF Application using the MVVM pattern
  5. Binding to methods encapsulated in an ICommand
  6. Simplifying the WPF TreeView by Using the ViewModel Pattern
  7. A Progress Bar using WPF’s Progress Bar Control, BackgroundWorker, and MVVM

Visual Studio Helps

  1. A Hello World template of a WPF application using MVVM
  2. A snippet for Properties in a ViewModel

WPF and MVVM Problems

  1. WPF NavigationService blanks PasswordBox.Password, which breaks the MVVM PasswordHelper

A snippet for Properties in a ViewModel

If you are using MVVM you probably should create a snippet very similar to the following to save time.

C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC#\Snippets\1033\Visual C#\propvm.snippet

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="">
	<CodeSnippet Format="1.0.0">
			<Description>Code snippet for property and backing field for a ViewModel that calls NotifyPropertyChanged.</Description>
			<Author>Jared Barneck</Author>
					<ToolTip>Property type</ToolTip>
					<ToolTip>Property name</ToolTip>
			<Code Language="csharp"><![CDATA[public $type$ $property$
		get { return _$property$;}
			_$property$ = value;
	} private $type$ _$property$;

A quick overview of MVVM

Model View ViewModel (MVVM) is a design pattern based on Model View Controller (MVC) but specifically tailored to Windows Presentation Foundation (WPF).

MVVM is not a framework per se but many frameworks have been created. Here is a list of MVVM Frameworks from Wikipedia.

See the Wikipedia site here: Open Source MVVM Frameworks.

Another blog, has some basic information on many of these here: A quick tour of existing MVVM frameworks

A framework is actually not necessary to implement MVVM and you should seriously consider whether using one is right for your WPF application or not. Many applications do not need much of the features the frameworks provide. However, there are two common classes that all MVVM frameworks contain. These are ViewModelBase and RelayCommand. Though some frameworks may give them different names or implement them slightly differently, they all have these classes. For example, MVVM Foundation names the ViewModelBase differently. It is called ObservableObject, which is more appropriate because it is incorrect to assume that all objects that implement INotifyPropertyChanged are going to be ViewModel objects.

Instead of installing and using an MVVM framework, you could simply include these classes in your application, as these are all you need to implement MVVM.

  • ObservableObject
  • RelayCommand

While these two classes are enough, you may want to investigate how different MVVM Frameworks implement and what else they implement and why. You may find that another feature implemented is exactly what you need in your application and knowing about it could save you time.