Beginning LightSwitch in VS 2013 Part 6: More Control! Customizing the app with JavaScript & CSS

Beginning LightSwitch in VS 2013 Part 6: More Control! Customizing the app with JavaScript & CSS

Rate This
  • Comments 22

NOTE: This is the Visual Studio 2013 update of the popular Beginning LightSwitch article series. For previous versions see:


Welcome to Part 6 of the Beginning LightSwitch in Visual Studio 2013 series! In parts 1 thru 5 we built an Address Book application and learned all about the major building blocks of a Visual Studio LightSwitch application -- entities, relationships, screens, queries and user permissions. If you missed them:

In this post I want to talk about some of the different ways you can customize your HTML client application by adding JavaScript code and CSS.

As you’re probably learning, LightSwitch is all about building mobile business solutions quickly -- defining your data models & business rules and visually creating screens with a set of built-in controls. It does all the boring plumbing so you can concentrate on the real value of your applications. But LightSwitch also allows for all sorts of customizations so you don’t hit that infamous “glass ceiling”. With the HTML client we can take advantage of the huge web ecosystem already out there, so adding customizations can be as easy as finding the JavaScript library you want and wiring it up to your app. 

LightSwitch produces single-page applications (SPAs) based on jQuery and jQueryMobile. These are the fundamental libraries used in the HTML client. LightSwitch then provides data/data binding & query capabilities on top of that in the msls.js scripts.  jQueryMobile CSS is used to control the look and feel of the application.

These files are available to you in the HTML client project. The stylesheets are located in the Content sub-folder and the JavaScript files are in the Scripts sub-folder:

image

For an introduction to jQuery and its syntax in the context of the LightSwitch HTML client see:
Introduction to jQuery for App Customization

Let’s take a look at some of the more interesting ways to quickly customize the HTML client.

Changing the Theme

The HTML Client comes with two themes “in the box” that you can use as-is, or completely change for your needs – a light theme and a dark theme. By default, the light theme is used for new projects. To change the theme to the dark theme, open up the default.htm file in the HTML Client project and change the following:

<!-- Change light-theme-2.0.0.css and msls-light-2.0.0.css to dark-theme-2.0.0.css 
and msls-dark-2.0.0.css respectively to use the dark theme. Alternatively, you may
replace light-theme-2.0.0.css with a custom jQuery Mobile theme. -->
<link rel="stylesheet" type="text/css" href="Content/dark-theme-2.0.0.css" /> <link rel="stylesheet" type="text/css" href="Content/msls-dark-2.0.0.css" />

Let’s apply this change to the Address Book app we’ve been building in this article series. When we run our app we now see the dark theme which has a black/grey background with white text and icons.

image 

Using ThemeRoller

Of course we’re not limited to these two themes, we can design our own. However, if you’re not design savvy or a CSS wiz, I encourage you to use jQueryMobile ThemeRoller to save you loads of time.

To start using ThemeRoller head to http://jquerymobile.com/themeroller/. To make it easy, you can import a stylesheet and then just tweak the elements you want. So in Visual Studio open the stylesheet we’re using /Content/dark-theme-2.0.0.css and copy all the contents into your clipboard. Using ThemeRoller, select version 1.3, click the Import button at the top of the screen, paste in the CSS, and then click Import:

image

This will load the dark theme into a swatch on the design surface. Now you can customize any of the elements by changing the properties on the left. Alternatively, you can select from a variety of pre-built themes and colors and simply drag them onto the swatch.

image

When you’re finished, export the theme by clicking on the Download button at the top of ThemeRoller and naming the new theme. This will download a ZIP with your theme (the ZIP includes a version that is readable and a min version that has the whitespace taken out).

Extract the contents of the ZIP, and in the theme folder, copy the CSS file (I named mine orange-theme), and paste it back in Visual Studio into the Content folder with the other stylesheets. Finally open up default.htm and replace the dark theme with ours.

    <link rel="stylesheet" type="text/css" href="Content/orange-theme.css" />

Branding

As an extension to changing the theme, you probably also want to add your company or product logo to your app. If you don’t want to dive into the CSS to do this, you can simply replace the stock images. One is displayed while the app is loading and the other displays on the top left of your home screen.

Just open up the Content\Images folder and replace the user-logo.png and user-splash-screen.png.

image

Applying this to our Address Book app gives us a nice polished look:

image

Visual Indicators on Data with CSS

Often times in business applications we need to do some UI validation, like changing the color of data based on its value. This needs to happen on the client. LightSwitch gives you hooks on controls in the screen designer so that you can either make changes to the control or completely render it yourself, depending on what you are trying to do.

Say we want to change the color of our contacts on our Home screen based on whether they are Male or Female. We can do this using the _postRender method on the Row Template of the Contact List. Open up the BrowseContacts screen, select the Contact Rows Layout, then drop down the “Write Code” button and select the _postRender method.

image

The method is passed two parameters, the element is the DOM element and contentItem is the screen’s content item in the content tree. The contentItem.value is the Contact entity in our example.

We’re going to want to adorn the element with a particular style so we can use the jQuery addClass method on the element.

image

First let’s create the styles we want. Notice that there’s a user-customization.css in the Content folder. Here is where you can tweak some of the common styles as well as add your own. Let’s add:

.male { background-color: blue; }
.female { background-color: purple; }

Now back in the _postRender you can add the code to check for the Gender value and apply the right style.

myapp.BrowseContacts.RowTemplate_postRender = function (element, contentItem) {
    // Write code here.
    if (contentItem.value.Gender == "M") {
        $(element).addClass("male");
    } else {
        $(element).addClass("female");
    }    
};

When we run it we can see our styles applied correctly:

image

However data likes to change in a business application :-). In this particular case, a contact’s gender probably won’t change, but what if we made a mistake when entering a contact? If you want the visual style to update when the data value changes, use the dataBind method to handle this.

This code will set up our function to be called anytime the Gender changes.

myapp.BrowseContacts.RowTemplate_postRender = function (element, contentItem) {
    // Write code here.
    contentItem.dataBind("value.Gender", function ()
    {
        if (contentItem.value.Gender == "M") {
            $(element).addClass("male");
            $(element).removeClass("female");
        } else {
            $(element).addClass("female");
            $(element).removeClass("male");
        }    
    });
};

Customizing the UI with Custom Controls

You can also take over the complete rendering of controls on screens yourself in order to inject anything you want into the DOM. Since LightSwitch HTML apps are based on jQuery and jQueryMobile, there are a plethora of plugins available for you to use in LightSwitch. Which ones you use totally depends on what you want to provide to your users and the devices that you need to support.

First, add a custom control to your screen where you want it in the content tree. Then drop down the write code button and select the _render method. For a simple example, say we want to add some text to our browse contacts screen under the list of contacts. First add the custom control:

image

Then select the data you want to pass in the contentItem parameter. The default is the entire screen, but you could select other data items available on the screen.

image

Then select the _render method and write your code.

image

For this simple example, let’s just write out the number of contacts found. Because data is loaded asynchronously, we need to use the dataBind trick again so that our code fires after the Contacts are loaded on the screen.

myapp.BrowseContacts.Contacts_render = function (element, contentItem) {
    // Instead of Screen, we passed Contacts as the contentItem. 
    var contacts = contentItem.value;

    // Set up the callback function to fire after the data is loaded.
    contentItem.dataBind("value.isLoaded", function ()
    {
        if (contacts.isLoaded) {
            //Create the HTML control
            var template = $("<b> " + contacts.count + " contacts found.</b>");
            //Append it to the DOM
            template.appendTo($(element));
        }
    });   
};

In action:

image

More Resources

There are a lot of articles out there on how to implement more advanced controls. I encourage you to check these out.

Well that wraps up the Beginning LightSwitch in Visual Studio 2013 series! Thanks for reading and have fun building mobile business apps with LightSwitch! And for more information, please visit the LightSwitch Developer Center and the LightSwitch Team Blog.

Enjoy!

Download the Completed Sample App

Leave a Comment
  • Please add 2 and 4 and type the answer here:
  • Post
  • @Yann -- Thanks! It's great to "see" you again :-)

  • Hi Beth, I had some trouble with adding custom control. When I run it, I see "0 contacts found. 6 contacts found" below the list. since I have 6 contacts. it seems the app is counting twice the no of contacts.

  • its ok now. I re-started VS and it is working now

  • I use the same html design and silverligth same database?

  • I worked through the whole series using VS2012.4 with support for the HTML Client. However I couldn't get the custom control showing the number of contacts to display. (I wish the context menu didn't overlay the screen design tree in the figure above.) I then used the link at the bottom of the article to downloaded the completed sample app, so I could examine the Browse Contacts screen with the custom control added. I unzipped it to a temp folder (so as not to conflict with my own solution by the same name) - however it wouldn't load, and then when I tried to re-open my own solution that was broken too! I WISH THERE HAD BEEN A WARNING ABOUT OPENING THE DOWNLOAD, IF IT WAS ONLY GOOD IN VS2013 AND MIGHT CLOBBER AN EXISTING SOLUTION WITH THE SAME NAME. If this page is still being monitored any advice would be appreciated.

  • Hi Laura,

    Sorry you're having trouble but there should be no effect on your solution if you downloaded the sample to a separate location. In fact, the VS2013 solution shouldn't have even opened in VS2012. What was your exact error?

    -Beth

  • Hello Beth,

    I don't recall the exact error; something or other was missing, and the solution was totally unable to load. The solution explorer was empty except for the name. I tried it a couple of times closing VS2012 and re-opening in between attempts. However I resolved it by navigating to the ContactManager.ls3proj file and opening that! All my work was still there, and now the solution opens too. (go figure)

    Although it's not terribly important, I still haven't figured out why the custom control line doesn't display.

    Thank you for continuing the support on this sample. The tutorial was excellent. I am trying LightSwitch as a proof of concept for relatively simple data entry apps, and as a way to get acquainted with mobile app dev.

    -LG

Page 2 of 2 (22 items) 12