BusinessRx Community

Dedicated to the advancement of software, technology and the people who devote their lives to it.

Welcome to BusinessRx Community Sign in | Join | Help
in Search

BusinessRx Reading List

These blog entries are written by industry experts and leaders. We consider this content to be a good read for any software developer or web technologist.

Browse by Tags

All Tags » Tips and Tricks » Silverlight   (RSS)

  • Tip/Trick: Creating and Using Silverlight and WPF User Controls

    One of the fundamental design goals of Silverlight and WPF is to enable developers to be able to easily encapsulate UI functionality into re-usable controls.

    You can implement new custom controls by deriving a class from one of the existing Control classes (either a Control base class or from a control like TextBox, Button, etc).  Alternatively you can create re-usable User Controls - which make it easy to use a XAML markup file to compose a control's UI (and which makes them super easy to build).

    In Part 6 of my Digg.com tutorial blog series I showed how to create a new user control using VS 2008's "Add New Item" project item dialog and by then defining UI within it.  This approach works great when you know up front that you want to encapsulate UI in a user control.  You can also use the same technique with Expression Blend.

    Taking Existing UI and Encapsulating it as a User Control

    Sometimes you don't always know you want to encapsulate some UI functionality as a re-usable user control until after you've already started defining it on a parent page or control.

    For example, we might be working on a form where we want to enable a user to enter shipping and billing information.  We might begin by creating some UI to encapsulate the address information.  To-do this we could add a <border> control to the page, nest a grid layout panel inside it (with 2 columns and 4 rows), and then place labels and textbox controls within it:

    After carefully laying it all out, we might realize "hey - we are going to use the exact same UI for the billing address as well, maybe we should create a re-usable address user control so that we can avoid repeating ourselves". 

    We could use the "add new item" project template approach to create a blank new user control and then copy/paste the above UI contents into it. 

    An even faster trick that we can use within Blend, though, is to just select the controls we want to encapsulate as a user control in the designer, and then "right click" and choose the "Make Control" menu option:

    When we select the "Make Control" menu item, Blend will prompt us for the name of a new user control to create:

    We'll name it "AddressUserControl" and hit ok. This will cause Blend to create a new user control that contains the content we selected:

    When we do a re-build of the project and go back to the original page, we'll see the same UI as before - except that the address UI is now encapsulated inside the AddressUserControl:

    We could name this first AddressUserControl "ShippingAddress" and then add a second instance of the user control to the page to record the billing address (we'll name this second control instance "BillingAddress"):

    And now if we want to change the look of our addresses, we can do it in a single place and have it apply for both the shipping and billing information.

    Data Binding Address Objects to our AddressUserControl

    Now that we have some user controls that encapsulate our Address UI, let's create an Address data model class that we can use to bind them against.  We'll define the class like below (taking advantage of the new automatic properties language feature):

    Within the code-behind file of our Page.xaml file we can then instantiate two instances of our Address object - one for the shipping address and one for the billing address (for the purposes of this sample we'll populate them with dummy data).  We'll then programmatically bind the Address objects to our AddressUserControls on the page.  We'll do that by setting the "DataContext" property on each user control to the appropriate shipping or billing address data model instance:

    Our last step will be to declaratively add {Binding} statements within our AddressUserControl.xaml file that will setup two-way databinding relationships between the "Text" properties of the TextBox controls within the user control and the properties on the Address data model object that we attached to the user control:

    When we press F5 to run the application we'll now get automatic data-binding of the Address data model objects with our AddressUserControls:

    Because we setup the {Binding} declarations to be "Mode=TwoWay", changes users make in the textboxes will automatically get pushed back to the Address data model objects (no code required for this to happen). 

    For example, we could change our original shipping address in the browser to instead go to Disneyland:

    If we wire-up a debugger breakpoint on the "Click" event handler of the "Save" button (and then click the button), we can see how the above TextBox changes are automatically reflected in our "_shippingAddress" data model object:

    We could then implement the SaveBtn_Click event handler to persist the Shipping and Billing Address data model objects however we want - without ever having to manually retrieve or manipulate anything in the UI controls on the page.

    This clean view/model separation that WPF and Silverlight supports makes it easy to later change the UI of the address user controls without having to update any of our code in the page.  It also makes it possible to more easily unit test the functionality (read my last post to learn more about Silverlight Unit Testing).

    Summary

    WPF and Silverlight make it easy to encapsulate UI functionality within controls, and the user control mechanism they support provides a really easy way to take advantage of this.  Combining user controls with binding enables some nice view/model separation scenarios that allow you to write very clean code when working with data.

    You can download a completed version of the above sample here if you want to run it on your own machine. 

    To learn even more about Silverlight and WPF, check out my Silverlight Tutorials and Links Page.  I also highly recommend Karen Corby's excellent MIX08 talk (which covers User Controls, Custom Controls, Styling, Control Templates and more), which you can watch online for free here.

    Hope this helps,

    Scott

  • July 4th Links: ASP.NET, ASP.NET AJAX, Visual Studio, Silverlight and IIS7

    I've fallen behind on my weekly link-listing series - apologies for the delay.

    ASP.NET

    • ASP.NET RSSToolkit 2.0 Released: One of the cool projects for ASP.NET 2.0 that was released last year was this free RSS Toolkit - which makes consuming and exposing RSS feeds in ASP.NET super easy (you can even databind any ASP.NET control against them).  The team working on the CodePlex project has recently released V2 of the RSSToolkit.  You can learn all about it and download it here.

    • Building a Custom Database Driven Site Map Provider: Scott Mitchell has written a great article on how to implement your own site map provider for ASP.NET that is populated from a database (instead of statically from an XML file).  You can learn more about the ASP.NET 2.0 SiteMap system from this older blog post of mine here.

    • .NET DateTime and Number Format String Cheat Sheet: If you are like me, you might have trouble remembering all of the standard format strings you can pass to the String.Format() method and/or the Eval() databinding method in ASP.NET to generate the appropriate string output from a DateTime or Numeric datatype.  This PDF cheatsheet is a useful one to download and save to quickly look these format strings up.  John has some other really useful .NET PDF cheatsheets he has also created that you might like to download here.

    • Profile Support for ASP.NET Web Application Projects: VS 2005 Web Application Projects can't directly access the strongly-typed ASP.NET "Profile" object that web site projects support.  This VS add-in supports the ability to generate a strongly typed profile class to accomplish this.  You can read this great series of posts to learn more about how to use the ASP.NET 2.0 Profile system.  I have it on my list of tips/tricks posts to-do to cover using this VS add-on as well.

    • ASP.NET Photo Handler: Bertrand has posted a cool photo album HttpHandler for ASP.NET that allows you to easily drop images into a web directory and automatically generate a nice photo album of them (complete with EXIF information, stack sorting icons, etc).  Might be very useful for people enjoying holidays this summer.  Download the code here.

    • BlogEngine.NET: This is a new open source blog engine for ASP.NET that Mads Kristensen has helped start up, and which I've heard a lot of good things about.  You can read about its features here, and download it here.

    ASP.NET AJAX

    • ScriptDoc 1.0 Available: Bertrand Le Roy has published a cool ScriptDoc utility that extracts documentation from JavaScript files and packages it into XML that can be consumed by documentation building tools.  A very useful tool as you start to build up your own JavaScript libraries.

    Visual Studio

    • GhostDoc 2.1.1 Released: GhostDoc is a free add-in for Visual Studio 2005 (and now 2008) that automatically generates default XML documentation comments for code you write in C# or VB.  It can automatically re-use existing documentation inherited from base classes or implemented interfaces, or generate initial documentation by deducing comments from the name and type of the member signature. You can learn more about it and download it for free here.

    Silverlight

    • Silverlight Tutorials: Michael Schwarz has a great blog where he writes regularly about Silverlight.  This tutorials link points to a bunch of great Silverlight content.

    IIS 7

    • IIS 7.0 is now running all of Microsoft.com: One of the things we push at Microsoft is to "dogfood" our products on our high volume sites when they enter the beta cycle.  As of a few weeks ago, all of the web servers running www.microsoft.com are now running on IIS7 and Windows 2008 Server Beta3.  These servers host 500+ virtual roots and 350 ASP.NET applications, and handle 300,000 concurrent connections.  IIS7 is going to be an awesome release.

    • IIS 7.0 on Server Core: Bill Staples blogs about some of the new IIS7 enhancements that appear with the June CTP of Windows 2008 Server.  One of the big features that is now supported is the ability to install IIS7 on "server core" - which is a low footprint installation of Windows 2008 Server that lays down just the minimal footprint needed to boot (meaning no GUI shell).  This lowers the resources required on servers, and even more importantly means that servers don't need to be updated if a patch is released for a component not installed on the server (which lowers the downtime of servers).  ASP.NET and the .NET Framework aren't supported yet in server core configurations - but will be in the future.

    Hope this helps,

    Scott

    P.S. I'm out on vacation this week, so please excuse delays on email and comment feedback.

  • Tip/Trick: Supporting Full Screen Mode with Silverlight

    One of the nice features that Silverlight supports is the ability to go "full screen" and effectively take over the entire screen of a computer (hiding everything else from sight - including the browser frame).  This can be very useful when building immersive UI experiences, games, rich video players, etc.

    For a nice example of this feature in action, make sure to check out the Fox Movies Sample on www.silverlight.net:

    Once the page loads and the movie starts playing, double-click on the video surface in the middle to switch into full-screen mode (note: the screen-shot above is not in full-screen but rather browser mode).  You can then hit the escape key to switch back into normal browser viewing.

    How to Implement Full Screen Mode with Silverlight 1.1 using .NET

    One of the questions I've seen a few people ask is "how can you implement full screen-mode when building Silverlight applications using .NET?"  The good news is that the answer is actually pretty easy:

    1) First add an input driven event handler to your application (for example: a mouse down or keyboard event handler).  For security reasons Silverlight doesn't allow developers to switch an application into full-screen mode on first application load (you don't want an application to spoof you).  So you'll instead need to trigger full-screen mode in response to a user action.

    2) Within your input event handler set the BrowserHost.IsFullScreen property to true (note: the BrowserHost class lives within the System.Windows.Interop namespace).  This will cause Silverlight to switch into full screen mode.  Setting this property to false will return it back to normal browser mode.

    Simple Full Screen Mode Sample

    You can download a simple Silverlight full screen-mode sample I put together written in C# here

    When you run the sample it will load a super simple Silverlight application within the browser and display a text message prompting you to click it to switch into full-screen mode:

    If you click the "Click for Full Screen" text, the application will switch into full-screen mode - which will hide everything else running on the system and take over the entire screen:

    When you switch into full-screen mode, Silverlight will display a user message blurb that will pop-up on the screen for a few seconds and instruct the user that they can press the escape key to switch back into browser mode.  After a few seconds this message will disappear and only your content will be visible.  In my sample above I also allow the user to click on the "Click to Return to Browser" text and switch back into browser mode as well.

    Walkthrough the Simple Full Screen Mode Code

    The code to implement the above sample is pretty simple. 

    To begin with we can open and edit the root .XAML file for the application, and add a UI element to it that we want to use to trigger the full-screen mode.  In the sample above I used a <TextBlock> control that I named "MyMessage".  Below is all of the XAML for the entire application:

    The below screen-shot shows the code-behind for the .XAML file above - and contains all of the code for the entire application:

    Within the application's Page_Loaded() event handler above I am wiring up two event handlers: 

    MyMessage_MouseLeftButtonDown - This event handler will execute anytime a user clicks on the TextBlock message control I added into my XAML file.  Within this event handler I'm simply toggling the BrowserHost.IsFullScreen property to true or false depending on whether or not it is already in full screen mode.

    BrowserHost_FullScreenChange - This event handler will execute anytime Silverlight switches between full screen and browser mode.  It provides a good place to add logic to update the UI when this happens.  In the example above I am changing the text on the TextBlock control.  I could also have optionally resized controls and/or moved them around the screen to new coordinate positions. Currently the Silverlight 1.1 Alpha doesn't have layout manager support, so controls won't automatically re-position unless you write code to manage this yourself (don't worry - layout manager controls for Silverlight like in the desktop WPF version are coming). 

    In addition to the IsFullScreen property, BrowserHost class has a number of additional properties and events that are very useful:

    The ActualHeight and ActualWidth properties are particularly useful to lookup the screen dimensions when you switch into full-screen mode - which you can then use when positioning and scaling your UI controls on the page.

    Summary

    Supporting full-screen mode within Silverlight applications is pretty easy to enable, and offers the ability to provide a nice, immersive user experience. 

    To learn more about Silverlight, please read my comprehensive Silverlight announcement post as well as visit the www.silverlight.net community site.

    To watch me walkthrough building a Silverlight application from scratch using .NET and Visual Studio "Orcas", please watch this video here.

    Hope this helps,

    Scott

Powered by Community Server, by Telligent Systems
'