Blog Archives

Getting Started with the MVVM Pattern in Silverlight Applications

With the increasing popularity of Silverlight as an application development framework the discussion of patterns has grown louder and louder. Fortunately the majority of developers building Silverlight applications have agreed on a pattern that fits well in the Silverlight world called Model-View-ViewModel (MVVM). The MVVM pattern allows applications to be divided up into separate layers that provide multiple benefits ranging from better code re-use to enhanced testing capabilities. This post will explain key concepts found in the MVVM pattern and attempt to present them in a way that is easy to understand. I’ll show some code along the way to demonstrate how the MVVM pattern can be used and provide a few alternatives when it comes to binding data. The code shown later in the post can be downloaded here.

Getting Started with the MVVM Pattern

The MVVM pattern defines three key parts including the Model, the View and the ViewModel. The following image shows a slide from a Silverlight course we offer that sums up the role of each part of the MVVM pattern in a concise way:

clip_image002

Looking through the description of each part you can see that the Model represents the business domain which includes the model classes used (Customer, Order, etc.), data access code and business rules. In general you can think of the Model as representing the entities that live on the server as well as the objects that are responsible for interacting with the data store your application uses and filling entities with data. While some people feel that the Model represents only the model classes (classes like Customer, Order, etc.) used in the application I personally think of it more broadly and include data access code and business rules in the Model definition. Silverlight applications will call into the Model code through services written using WCF, ASMX, REST or even custom solutions.

The View in MVVM represents the Silverlight screens that you build. This includes the XAML files and the code-beside files that are responsible for showing data to end users. The View’s responsibilities include displaying data and collecting data from end users. A given View isn’t responsible for retrieving data, performing any business rules or validating data.

The ViewModel acts as the middle-man between the View and the Model. It's responsible for aggregating and storing data that will be bound to a View. For example, a ViewModel may contain a List<State> property and a List<Person> property that may be bound to two ComboBox controls in a View. The ViewModel will retrieve the values held by these two properties from the Model. By using a ViewModel the View doesn't have to worry about retrieving data and knows nothing about where data comes from.

Additional players may be added into the Model-View-ViewModel mix to help segregate code even further. For example, I normally create a service agent class that is responsible for making calls from Silverlight to remote services. The service agent is responsible for initiating the service call, capturing the data that’s returned and forwarding the data back to the ViewModel. By doing this the ViewModel classes can delegate data gathering responsibilities to the service agent. A given service agent can also be re-used across multiple ViewModel classes as needed. The following image shows how the service agent can be integrated into the MVVM pattern:

clip_image004

 

When developers first start building Silverlight applications they typically add all of the code for the application into the XAML’s code-beside file (MainPage.xaml.cs for example). Although this approach certainly works, by following the MVVM pattern you can take advantage of several inherent benefits including better code re-use, simplified maintenance, more modular code and enhanced testing support. I’ll focus on the overall benefits achieved by building applications that are based on the MVVM pattern throughout the rest of this article.

The Model

There are many different ways that the Model can be created including using Microsoft's Entity Framework or LINQ to SQL technologies, nHibernate, PLINQO, SubSonic, custom solutions and more. The technology chosen is generally unique to a given company's development policies so I'm not going to go into a discussion of the pros and cons of each technology here. What's important is that one or more classes used by a Silverlight application are "modeled" using tools or by writing code by hand. This involves defining all of the properties that each class will expose. A simple example of a Model class is shown next:

public class Person
{
    public string FirstName { get;set;}
    public string LastName { get;set; }
    public int Age { get; set; }
}

 

Once the Model classes are in place they’ll need to be populated with data from a data store which can be done by writing custom code or using ORM frameworks that handle mapping query results to object instances. Services will also need to be written to expose one or more of the Model classes used in a Silverlight application which can be done using WCF, ASMX or even custom REST services.

The View and ViewModel Classes

Once the Model is ready to go the View and ViewModel classes can be created. As mentioned earlier, a View represents a Silverlight screen that end users interact with which includes the XAML file and the associated code-beside file. Rather than adding all of the code to call the Model and retrieve data directly into the View’s code-beside file, the View will rely on a ViewModel class to retrieve data and then bind to the properties of the ViewModel.

ViewModel classes should implement an interface that’s available in Silverlight called INotifyPropertyChanged which defines a single event named PropertyChanged. This event is used to notify different Silverlight bindings that data has changed for one or more properties so that controls can be updated automatically. Although INotifyPropertyChanged can be implemented directly on a ViewModel class, your application may have multiple ViewModel classes in it and writing the same code over and over tends to get old. Creating a base ViewModel class that handles implementing INotifyPropertyChanged is useful to minimize code and allow more re-use to occur in applications. The following code shows a class named ViewModelBase that implements the INotifyPropertyChanged interface. The class also provides an OnNotifyPropertyChanged method that can be used to raise the PropertyChanged event.

public class ViewModelBase : INotifyPropertyChanged
{
    protected void OnNotifyPropertyChanged(string p)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(p));
        }
    }

    public bool IsDesignTime
    {
        get
        {
            return (Application.Current == null) || (Application.Current.GetType() == typeof(Application));
        }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
}

 

A ViewModel class can derive from ViewModelBase and automatically take advantage of the INotifyPropertyChanged interface. An example of a ViewModel class named PeopleViewModel that derives from the ViewModelBase class and defines several properties and methods is shown next:

public class PeopleViewModel : ViewModelBase
{
    IServiceAgent _ServiceAgent;
    Person _Person;
    ObservableCollection<Person> _People;

    public PeopleViewModel() : this(new ServiceAgent()) {}

    public PeopleViewModel(IServiceAgent serviceAgent)
    {
        if (!IsDesignTime)
        {
            _ServiceAgent = serviceAgent;
            GetPeople();
        }
    }

    #region Properties

    public Person Person
    {
        get
        {
            return _Person;
        }
        set
        {
            if (_Person != value)
            {
                _Person = value;
                OnNotifyPropertyChanged("Person");
            }
        }
    }

    public ObservableCollection<Person> People {
        get
        {
            return _People;
        }
        set
        {
            if (_People != value)
            {
                _People = value;
                OnNotifyPropertyChanged("People");
            }
        }

    }

    #endregion        

    public void GetPeople()
    {
        _ServiceAgent.GetPeople((s,e) => this.People = e.Result);
    }

    public void UpdatePerson()
    {
        _ServiceAgent.UpdatePerson(this.Person, (s, e) =>
        {
            PeopleEventBus.OnOperationCompleted(this, new OperationCompletedEventArgs { OperationStatus = e.Result });
        });
    }
}


Looking through the code you'll see that PeopleViewModel defines two fields, two properties and two methods. Each property raises the PropertyChanged event as the set block is called by calling the OnNotifyPropertyChanged method defined in ViewModelBase. This notifies any controls bound to the properties that the values have changed which allows them to update the data they display automatically. 

Looking at the first constructor in PeopleViewModel you’ll see that it forwards the call to a secondary constructor that accepts a parameter of type IServiceAgent. Why have two constructors? This approach allows testing frameworks to pass in different types of service agents to the ViewModel when running tests. When the ViewModel is called at runtime the parameterless constructor will be called and an instance of a ServiceAgent class (shown next) will be passed as the IServiceAgent parameter. From there, once the service agent object is passed into the ViewModel’s constructor a call to a method named GetPeople is made which invokes a method on the service agent and passes a callback delegate. The WCF service is then called by the service agent and the results are assigned to the People property.

 

public interface IServiceAgent
{
    void GetPeople(EventHandler<GetPeopleCompletedEventArgs> callback);
    void UpdatePerson(Person p, EventHandler<UpdatePersonCompletedEventArgs> callback);
}

public class ServiceAgent : IServiceAgent
{
    public void GetPeople(EventHandler<GetPeopleCompletedEventArgs> callback)
    {
        PeopleServiceClient proxy = new PeopleServiceClient();
        proxy.GetPeopleCompleted += callback;
        proxy.GetPeopleAsync();
    }

    public void UpdatePerson(Person p, EventHandler<UpdatePersonCompletedEventArgs> callback)
    {
        PeopleServiceClient proxy = new PeopleServiceClient();
        proxy.UpdatePersonCompleted += callback;
        proxy.UpdatePersonAsync(p);
    }
}

 

Binding a ViewModel to a View

Now that the ViewModel class is defined it can be bound to a View. This can be done declaratively in XAML or imperatively through code in the View’s code-beside file. Imperative (or code-based) binding is typically accomplished by assigning a ViewModel instance to the layout root’s DataContext property as shown next:

this.LayoutRoot.DataContext = new PeopleViewModel();

An example of declaratively binding a ViewModel (which is my personal preference) to a View is shown next:

<UserControl x:Class="ViewModelExample.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:converter="clr-namespace:ViewModelExample"
    xmlns:viewModel="clr-namespace:ViewModelExample.ViewModel"
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
    <UserControl.Resources>
        <viewModel:PeopleViewModel x:Key="ViewModel" />
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" DataContext="{Binding Source={StaticResource ViewModel}}">
    </Grid>
</UserControl>

 

The ViewModel namespace is first referenced using an XML namespace prefix of "viewModel". The ViewModel is then defined in the UserControl's Resources section and given a key of "ViewModel" (note that any name can be chosen for the key). The key is important since it's used to hook the ViewModel to the DataContext of the layout root using the {Binding Source={StaticResource ViewModel}} syntax. The declarative binding will cause a new PeopleViewModel instance to be created at runtime which is then bound to the layout root's DataContext. Child controls of the layout root can then bind to properties on the ViewModel. An example of binding a ListBox to the ViewModel's People property and a StackPanel to the Person property is shown next:

<StackPanel Margin="20">
    <TextBlock Text="Binding Controls to a ViewModel" Margin="20,0,0,0" FontWeight="Bold" FontSize="12" />
        <ListBox x:Name="lbPeople" Margin="0,10,0,0" Height="250" Width="300" HorizontalAlignment="Left"
                 ItemsSource="{Binding People}" ScrollViewer.HorizontalScrollBarVisibility="Hidden"
                 SelectedItem="{Binding Person, Mode=TwoWay}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="100" />
                            <ColumnDefinition Width="100" />
                            <ColumnDefinition Width="100" />
                        </Grid.ColumnDefinitions>
                        <TextBlock Grid.Column="0" Margin="10" Text="{Binding FirstName}" />
                        <TextBlock Grid.Column="1" Margin="10" Text="{Binding LastName}" />
                        <TextBlock Grid.Column="2" Margin="10" Text="{Binding Age}" />
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <StackPanel DataContext="{Binding Person}">
            <TextBlock Text="First Name" Margin="0,10,0,0" />
            <TextBox Text="{Binding FirstName,Mode=TwoWay}" Width="100" Height="25" HorizontalAlignment="Left"/>
            <TextBlock Text="Last Name" />
            <TextBox Text="{Binding LastName,Mode=TwoWay}" Width="100" Height="25" HorizontalAlignment="Left"/>
            <TextBlock Text="Age" />
            <TextBox Text="{Binding Age,Mode=TwoWay}" Width="100" Height="25" HorizontalAlignment="Left"/>
        </StackPanel>
        <Button Margin="0,10,0,0" Click="Button_Click" Content="Submit" Height="20" Width="100" HorizontalAlignment="Left" />
</StackPanel>

 

The MVVM pattern provides a flexible way to work with data that encourages code re-use and simplifies maintenance. There’s much more that can be discussed with regard to the MVVM pattern in Silverlight such as event buses, commanding and dependency injection but I hope this post helps jumpstart the process of architecting and developing Silverlight applications. If you have specific Silverlight development concepts you’d like to see covered in future posts tweet me at @DanWahlin or add a comment below.

BugCamSmash – Motion Detection with Silverlight 4 Beta

At PDC09, we released Silverlight 4 Beta and announced one of the availability of, one of the most requested features, Web Cam Support.

Wanting to have fun with the new feature, I thought of a fun sample to create – smashing bugs with motion detection. First step was to get bugs to crawl across the screen. Next I added the WebCam with frame diff calculation, which was intensive so took advantage of the multiple thread support. And finally I added a little Mantis Boy avatar to visualize the smashing of the bugs.

Over the next few days I will post about how the code works and improvements made for performance. You can check out a video to see Mantis Boy in action, run the demo or download the source.

 

Learn how it was written:

 

*(warning this is Silverlight 4 Beta code, if you’re not currently setup to run the beta stick with the video)

Passing Multiple Records to a Stored Procedure in SQL Server

There are so many different ways to work with data that it can make your head spin.  Regardless of the technology, one thing I always try to do when working with databases is minimize the number of calls that are made.  I use ORM frameworks a lot so I have to make sure that my code doesn’t end up calling the database a ton and being overly “chatty”. 

My company is currently working on a large Silverlight 3 application for a customer and have a requirement to allow CSV file uploads through the application.  That’s pretty straightforward to do with Silverlight but in looking through the CSV file there can be 1000s of records and there is a lot of custom functionality around each record.  Initially I was going to handle the business rules and insertion for each row individually.  However, once I saw how many rows were involved I backed off my initial approach since that would mean a single file upload could trigger thousands and thousands of calls to the database which certainly isn’t efficient.  Instead of going that route I decided it would be better to pass all of the rows into a stored procedure and let it handle everything.  That way I can make a single database connection yet handle inserting (and updating and deleting based upon the business rules) many records. 

So how can you pass multiple records into a stored procedure?  Back in “the day” I’d pass in delimited strings and then parse them.  Although that technique probably wasn’t the most efficient, it got the job done.  With SQL Server 2005 and higher we have access to a much more efficient technique due to the availability of XQuery.  The current project I’m working on relies on SQL Server 2005 behind the scenes so that’s what I’ll focus on here.  Note that SQL Server 2008 allows .NET DataTable objects to be passed when using table value parameters as well in a stored procedure.  See www.codeproject.com/KB/database/sqlserver2008.aspx for an overview of the table value parameter functionality.

For the import I can serialize the list of records to XML and then pass them into a stored procedure.  It appears that you can pass an XmlDocument object from .NET if the stored procedure takes an XML input parameter type.  However, I never got it to work properly doing that so I pass a string containing serialized XML data and then load it into the XML data type.  The stored procedure can then use XQuery to convert the XML into actual rows.  Here’s some code that handles parsing a flat file, converting the data into a List<JobMaterialImport>, serializing the list into XML and then passing the serialized XML data to a stored procedure named ImportJobMaterials.

public List<ImportJobMaterialsResult> ImportJobMaterials(int jobID, Stream stream, string coNumber, string coDesc, string xmlMapFile)
{
    //Convert flat file to List<JobMaterialImport> using converter and XML mapping file
    //Mapping file passed from FlatFileHandler.ashx in web project
    FlatFileToObjectConverter<JobMaterialImport> converter = new FlatFileToObjectConverter<JobMaterialImport>(stream, xmlMapFile);
    List<JobMaterialImport> imports = converter.ConvertToList();
    imports = imports.Take(imports.Count - 2).ToList(); //last rows are bogus in flat-file

    //Generate XML and pass to sproc
    using (StringWriter sw = new StringWriter())
    {
        XmlSerializer xs = new XmlSerializer(typeof(List<JobMaterialImport>));
        xs.Serialize(sw, imports);
        try
        {
            //Pass materials into sproc
            string xml = sw.ToString().Replace("utf-16", "utf-8");
            return this.DataContext.ImportJobMaterials(xml, jobID, coNumber, coDesc).ToList();
        }
        catch (Exception exp)
        {
            Logger.Log("Error in JobManagementRepository.ImportJobMaterials", exp);
        }
    }
    return null;
}

 

The XML that’s generated from the code above looks like the following.  Security Note: We’ll assume that appropriate measures have been taken to clean the data and ensure it doesn’t contain any bad stuff related to injection attacks. That’s especially important if you’ll be running any dynamic SQL in your stored procedure.  I’m not, but I thought I’d be a good citizen and point it out…always sanitize your data with some Clorox before using it. :-)

<ArrayOfJobMaterialImport xmlns:xsi="www.w3.org/2001/XMLSchema-instance" xmlns:xsd="www.w3.org/2001/XMLSchema">
  <JobMaterialImport>
    <Area>BUILDING A</Area>
    <Phase>LIGHTING</Phase>
    <WorkCode>0</WorkCode>
    <WorkCodeTitle>Manually Assigned</WorkCodeTitle>
    <Description>4x1 1/2in. SQ BOX COMB KO</Description>
    <Quantity>2</Quantity>
    <TotalHours>10.46</TotalHours>
  </JobMaterialImport>
  <JobMaterialImport>
    <Area>BUILDING A</Area>
    <Phase>LIGHTING</Phase>
    <WorkCode>0</WorkCode>
    <WorkCodeTitle>Manually Assigned</WorkCodeTitle>
    <Description>#8x   3/4 P/H SELF-TAP SCREW</Description>
    <Quantity>4</Quantity>
    <TotalHours>0.28</TotalHours>
  </JobMaterialImport>
  <JobMaterialImport>
    <Area>BUILDING A</Area>
    <Phase>LIGHTING</Phase>
    <WorkCode>605</WorkCode>
    <WorkCodeTitle>Wiring and System Devices</WorkCodeTitle>
    <Description>1G TGL SWITCH PLATE - PLASTIC IVY</Description>
    <Quantity>2</Quantity>
    <TotalHours>0.89</TotalHours>
  </JobMaterialImport>
</ArrayOfJobMaterialImport>

 

Here’s what the stored procedure looks like:

 

CREATE PROCEDURE [ImportJobMaterials]
    @JobMaterialsXml AS VARCHAR(MAX),
    @JobID AS INT,
    @ChangeOrderNumber AS VARCHAR(10) = NULL,
    @ChangeOrderDescription AS VARCHAR(100) = NULL
AS
    BEGIN
        DECLARE @XML AS XML

        DECLARE @MaterialsTable TABLE
        (
            ID INT IDENTITY(1,1),
            Area VARCHAR(250),
            Phase VARCHAR(250),
            WorkCodeID INT,
            WorkCodeTitle VARCHAR(250),
            MaterialTitle VARCHAR(250),
            Quantity DECIMAL(18,2),
            TotalHours DECIMAL(18,2)
        )

        SELECT @XML = @JobMaterialsXml

        INSERT INTO @MaterialsTable (Area, Phase, WorkCodeID, WorkCodeTitle, MaterialTitle, Quantity, TotalHours)
        SELECT M.Item.query('./Area').value('.','VARCHAR(250)') Area,
               M.Item.query('./Phase').value('.','VARCHAR(250)') WorkCode,
               M.Item.query('./WorkCodeID').value('.','INT') WorkCodeID,
               M.Item.query('./WorkCodeTitle').value('.','VARCHAR(250)') WorkCodeTitle,
               M.Item.query('./MaterialTitle').value('.','VARCHAR(250)') MaterialTitle,
               M.Item.query('./Quantity').value('.','DECIMAL(18,2)') Quantity,
               M.Item.query('./TotalHours').value('.','DECIMAL(18,2)') TotalHours
        FROM @XML.nodes('/ArrayOfJobMaterialImport/JobMaterialImport') AS M(Item)

        --Process the data        
    END

Once the XML data comes in it’s converted into an XML data type using SELECT @XML = @JobMaterialsXml syntax.  The key part of the T-SQL code is the SELECT statement that grabs each value from the XML data type and looks for specific child nodes.  If the child nodes were attributes instead then you would do something like M.Item.value(‘@attributeName’,’DBType’).  Each JobMaterialImport node in the XML is located by the @XML.nodes(‘/ArrayOfJobMaterialImport/JobMaterialImport’) AS M(Item) code.  What’s nice about this approach is that a single call can be made to the database yet 1000s of records can be processed.  Not optimal for every situation, but exactly what I needed and fairly straightforward to use.

Use Bing Visual Search to Browse iPhone Applications [Search]

Microsoft’s Visual Search tool, introduced earlier this week, turns out to be a pretty helpful platform for browsing free and paid iPhone applications. It’s a trade-off: you won’t have to fire up iTunes, but you will have to install Silverlight.

Reader Anunay writes in with the link to turn Bing into a robust search for iPhone apps. From left-hand links, you can narrow your search by broad categories, specific prices, publishers, or other criteria. Hovering over an app icon gives you ranking, category, and release date information, and clicking an icon brings you to a Bing search page for that app—which, in turn, generally leads you to a developer's page and iTunes link. For those who don't like to (or can't) fire up iTunes to browse and search apps, it's a decent alternative, even if it requires installing a third-party plug-in. Thanks Anunay!






Cleaning Up the Disabled State of a Silverlight Control using Expression Blend

Silverlight provides the ultimate in flexibility when it comes to styling controls.  If you don’t like how something looks you can tweak the template in a tool like Expression Blend quickly and easily and get something completely different.  This post is geared towards those of you who may just be getting into Silverlight.  My goal is to demonstrate how easy it is to change controls using a simple example that I just went through on a client application.

Being able to change a control’s template comes in handy when you don’t like the built-in style used by the framework.  I’m working on a menu used in a client application and the disabled state of the HyperlinkButton control wasn’t looking too good.  I thought the control looked butt ugly and was unreadable in the disabled state.…just sayin’.  :-)   I wasn’t looking to do anything fancy, but did want to make it obvious that the control was disabled while still making it easy for the end user to read the text.  Here’s what the menu looked like when two HyperLinkButton controls were disabled using the built-in control template:

image

I don’t know about you, but “Edit Job” and “Job Plan” look pretty bad in my opinion.  They’re definitely disabled (or possibly just plain dead), but they could both look better.  As mentioned earlier, Silverlight allows any control to be changed by simply modifying the control’s template.  The easiest way to do this is to use Expression Blend although you can do it in Visual Studio 2008 by hand as well.  When the control to tweak is placed on the Blend design surface you can right-click on it and select Edit Template –> Edit a Copy:

image

From there you can give the new style a name, specify where it should be stored and then click OK:

image

Once the style is created you’ll be able to see it in Blend and locate an element named DisabledOverlay.  In my case this was the culprit of the ugliness. 

image

I ended up adjusting the Foreground color of the DisabledOverlay to black and set the Opacity to .4 using the properties window.  However, doing that isn’t quite enough.  The HyperlinkButton template places the DisabledOverlay TextBlock over the actual link content when the control is disabled.  That’s why you get the semi blurry effect because two pieces of text are showing.  I decided I wanted to hide the contentPresenter element when the control was disabled and just show the DisabledOverlay instead since it looked a lot cleaner.  Fortunately that’s quite easy to do.  Internally the control template uses the VisualStateManager to show and hide the DisabledOverlay.  I went into the disabled state and changed it to hide the contentPresenter.  That’s done by clicking on the States tab followed by the Disabled state:

image

Any changes you make to the contentPresenter are now tracked for that state so I clicked on contentPresenter and then set is Visibility property to Collapsed for the Disabled state:

image

Doing that modifies the disabled state.  Here’s what the XAML looks like (I cleaned it up slightly).  You can see that it causes the contentPresenter’s Visibility to be set to Collapsed:

<VisualState x:Name="Disabled">
    <Storyboard>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="DisabledOverlay" Storyboard.TargetProperty="Visibility" Duration="0">
            <DiscreteObjectKeyFrame KeyTime="0">
                <DiscreteObjectKeyFrame.Value>
                    <Visibility>Visible</Visibility>
                </DiscreteObjectKeyFrame.Value>
            </DiscreteObjectKeyFrame>
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="contentPresenter" Storyboard.TargetProperty="Visibility" Duration="0">
            <DiscreteObjectKeyFrame KeyTime="0">
                <DiscreteObjectKeyFrame.Value>
                    <Visibility>Collapsed</Visibility>
                </DiscreteObjectKeyFrame.Value>
            </DiscreteObjectKeyFrame>
        </ObjectAnimationUsingKeyFrames>
    </Storyboard>
</VisualState>
</VisualStateGroup>

 

From there I simply applied the style and newly created template to each HyperlinkButton control:

<HyperlinkButton Style="{StaticResource MenuHyperlinkButtonStyle}" Content="Job Plan" />


The end result is a menu that looks much better (in my opinion anyway) when the controls are disabled.  Here’s a before and after image:

Before:

image



After:

image


This is a really simple example of modifying control templates but you can literally tweak any aspect of a control to get things looking just like you want them to look.

 

Logo

For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit www.thewahlingroup.com.

Creating a Silverlight DataContext Proxy to Simplify Data Binding in Nested Controls

Data binding is one of my favorite features and something that I use a lot while building Silverlight applications.  Silverlight makes it really easy to bind data to different controls and move data from controls back into the original bound object without having to write any C# or VB code in many cases.  Here’s an example of binding a ComboBox control to an object that defines a property named Branches:

<ComboBox
    ItemsSource="{Binding Branches}"
    DisplayMemberPath="Title"/>


This code binds the ItemsSource property to the DataContext object’s Branches property and displays the Branch object’s Title property in the ComboBox.  The DataContext could be assigned directly to the ComboBox through code or could be assigned to a parent object.  If it’s defined on a parent then all children have access to the object. 

This works great as long as the ComboBox has access to the Branches property as shown in Figure 1 below (note that the Page shown in the figure is a Silverlight Page class or User Control not a web page).  However, figure 2 demonstrates a problem that can occur as the ComboBox control’s DataContext is changed to something other than the ViewModel object that defines the Branches property.  In this example a DataGrid binds to the Jobs property of the ViewModel and each row’s DataContext is a Job type.  The Job type doesn’t have a Branches property (the ViewModel object does obviously) so the ComboBox no longer has access to it for data binding.  Or does it?

Figure 1 – All Systems go for binding

Figure 2 – Houston, we have a problem

image image

 

Using a Static Resource When Binding Nested Controls


While the ComboBox can’t bind to the Branches property using the standard {Binding Branches} syntax when it’s nested in something like a DataGrid (or ListBox or another items control) it can still get to the ViewModel object’s Branches property with a few minor changes.  The first way that this little dilemma can be solved is to write code that assigns the ViewModel object’s Branches collection to each ComboBox in the LoadingRow event of the DataGrid.  This works but who wants to write code when you don’t have to?  The second way is to create a mini ViewModel class that each row binds to that references the Branches collection.  That’s also an option, but there’s a “codeless” way to do it as well that’s quite easy.  If the ViewModel object is defined in the Resources section of the Page or UserControl you can get to it using its key name directly in XAML.  Here’s an example of defining a the ViewModel object declaratively in XAML:

<UserControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:vm="clr-namespace:JobPlan.ViewModel;assembly=JobPlan.ViewModel"
    x:Class="JobPlan.View.UserControls.JobEdit">
    <UserControl.Resources>
        <vm:ViewModel x:Key="ViewModel" />
    </UserControl.Resources>

    ...

</UserControl>


A ComboBox control within a DataGrid row (or nested in another type of control) can get to the ViewModel object’s Branches property using the following binding syntax:

<ComboBox
    ItemsSource="{Binding Source={StaticResource ViewModel},Path=Branches}"
    DisplayMemberPath="Title"/>


This XAML code tells the ComboBox control to access a statically defined resource with a key of “ViewModel” and then find a property of that resource object named Branches.  Pretty cool because you don’t have to write any C# or VB code at all by using this solution which is great if you’re dealing with a lot of nested ComboBox controls.  For developers that don’t like defining their ViewModel objects in XAML you can always use an intermediary ViewModel lookup object when things need to be as loosely coupled as possible.

Now that you see how nested objects can get to properties defined at higher levels I can cover the main point of this post.  Everything mentioned to this point works great out of the box especially if you want to avoid writing code as much as possible.  However, there’s one final problem where the StaticResource binding trick won’t work.  Take a look at the figure below to get an idea of the problem:

image


If the DataGrid and nested ComboBox controls are moved into a User Control you can’t use the StaticResource keyword to get to the ViewModel object.  Why?  Because the ViewModel object is defined in the Resources of the parent not in the actual User Control itself.  You could of course write code to get to it and then bind the data (writing code is always an option but can quickly get out of control in larger applications with a lot of controls), but what if you want to bind everything declaratively in XAML?  I don’t know of a built-in way to do that (and I’ve asked many people and have yet to hear an answer that didn’t involve mini ViewModels for each row or writing code) so I ended up creating a fairly simple solution to address the problem. 

The DataContextProxy Class

When I first tried to solve this problem I figured I could define the ViewModel again up in the Resources of the nested User Control.  Try this and you’ll quickly realize that it doesn’t work because it’ll cause a new ViewModel object to be created and two will now be in memory (one for the parent and one for the child User Control).  I needed a way to get to the DataContext from the parent but couldn’t do it using Resources it seemed…without writing code anyway (on a side note, I’m not opposed to writing code at all but the application I’m working on encounters the problem defined here frequently and the code started to get ridiculous).  I started thinking about how the ScriptManagerProxy class works in ASP.NET AJAX and played around with something I now call the “DataContextProxy”.  I needed a way to get to the parent’s DataContext and came up with the following class that does just that:

 

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace JobPlan.Controls
{
    public class DataContextProxy : FrameworkElement
    {
        public DataContextProxy()
        {
            this.Loaded += new RoutedEventHandler(DataContextProxy_Loaded);
        }

        void DataContextProxy_Loaded(object sender, RoutedEventArgs e)
        {
            Binding binding = new Binding();
            if (!String.IsNullOrEmpty(BindingPropertyName))
            {
                binding.Path = new PropertyPath(BindingPropertyName);
            }
            binding.Source = this.DataContext;
            binding.Mode = BindingMode;
            this.SetBinding(DataContextProxy.DataSourceProperty, binding);
        }

        public Object DataSource
        {
            get { return (Object)GetValue(DataSourceProperty); }
            set { SetValue(DataSourceProperty, value); }
        }

        public static readonly DependencyProperty DataSourceProperty =
            DependencyProperty.Register("DataSource", typeof(Object), typeof(DataContextProxy), null);

        public string BindingPropertyName { get; set; }

        public BindingMode BindingMode { get; set; }

    }
}


The DataContextProxy class grabs the parent DataContext that flows down to the child User Control and binds it to a dependency property named DataSourceProperty.  The DataContextProxy object can be defined in the User Control’s Resource section as shown next:

<UserControl.Resources>
    <controls:DataContextProxy x:Key="DataContextProxy" />
</UserControl.Resources>


This allows the ViewModel defined in the parent to be accessed using XAML in the child User Control.  For example, a ComboBox control nested in a DataGrid can easily get to the Branches property using the following binding syntax:

 

<ComboBox
    DisplayMemberPath="Title"
    ItemsSource="{Binding Source={StaticResource DataContextProxy},Path=DataSource.Branches}" />


The binding syntax tells the ComboBox to bind to the statically defined DataContextProxy object’s DataSource property.  This allows the control to get to the original ViewModel object originally defined in the parent’s Resources section.  The syntax then says to bind to the Branches property of the ViewModel by using the Path property.

Wrapping it Up

Silverlight has a lot of nice data binding features but there will be times when you’ll run into a few road blocks as you’re developing applications.  In this post you’ve seen different techniques that can be used when binding nested controls to data objects and seen how the DataContextProxy object can be used.  Hopefully this will help some of you out down the road when you’re working with a lot of nested controls.

 

Logo

For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit www.thewahlingroup.com.

Building Line of Business Applications with Silverlight 3 – Pros and Cons

imageI’ve been hearing a lot of people talk about how Silverlight 3 can or can’t do various things lately throughout the blogosphere and Twitter.  The sad part is that some of the people giving their two cents about what Silverlight can’t do haven’t built a “real world” application so I’m not sure how their opinion carries any weight (I know because I’ve asked a few of them). Their list of cons are typically based on what they heard on Twitter or various rumors floating around.  As with any technology there are pros and cons and Silverlight is no exception.  The goal of this post is to talk through some of the pros and cons I’ve personally encountered while building a “real world”, enterprise-scale timesheet and job management application for a large electrical contracting company.  I’ll point out what has worked really well and what hasn’t so that people looking to move applications to Silverlight 3 can get an honest assessment on what can be done and what can’t be done.

The application my company is building has a lot of different screens (30+), integrates with the backend database using WCF, uses reporting services for reports and leverages many of the key features Silverlight 3 has to offer.  The existing application used by the client was written using Access Forms and is being ported to Silverlight 3 along with a bunch of new functionality.

Let’s start by going through what I personally feel are the pros and cons that Silverlight brings to the table for Line of Business (LOB) applications.

Silverlight 3 Pros

Here are some of the pros I’ve found as I’ve worked through the application:

  1. Excellent data binding support – my favorite feature.  This changes how you look at building applications and allows you to write data-centric code instead of control-centric code as with normal Web applications.  There’s a lot I could cover here but I wrote up a post awhile back that gives additional details about what I like.  Read it here.
  2. Server code and client code can written in the same language.  Business and validation rules can be shared between the client and server code base which definitely makes applications more maintainable into the future.
  3. A rich set of controls – I really like the controls available with the Silverlight SDK as well as those in the Silverlight toolkit.  There are a few (mentioned below) that can test your patience when you’re building a more involved application and not a simple demo.
  4. Support for just about any type of animation or effect you want.  Don’t need that in a LOB app?  I beg to differ.  You can get quite creative with how data is displayed with Silverlight and not be limited to simple slide, sizing or opacity animations.  I’ll show an example of what I call the “card flow” interface later in this post and show how it allows managers to get to timecards faster and easier than before.
  5. Excellent designer support through Expression Blend 3 – Visual Studio 2008 is great for coding but doesn’t provide any design-time features for Silverlight 3.  Not a big deal….you can use Expression Blend 3 which provides a great interface for designing your applications.  The new SketchFlow application can even be used to prototype applications upfront and get customer feedback more quickly and easily than in the past.
  6. Easy to integrate distributed data using WCF, ASMX, REST, ADO.NET Data Services, .NET RIA Services, etc.  The application that I’m working on leverages WCF as well as some dynamic code on the client-side to make calls to the service.  It works great and FaultExceptions can even be handled now with Silverlight 3.
  7. Desktop-style application with a web deployment model – Get the responsiveness of a desktop application that can be deployed right through the browser and even run on Macs.
  8. Support for styling of controls.  Silverlight 3 now allows styles to be changed on the fly and styles to be based on other styles.  If you don’t like how a control currently looks you can completely change it by using styles and control templates. 
  9. Out of browser support – This was a key reason why my client choose Silverlight 3.  They have a lot of remote workers that don’t always have access to the Internet and needed to be able to enter timesheets even when disconnected and then sync them later once a given employee has connectivity.
  10. Support for behaviorsBehaviors are very, very useful in Silverlight applications.  I needed to add mouse wheel scroll capabilities to a ScrollViewer control to simplify scrolling in a screen and did it within minutes by using a behavior (thanks to Andrea Boschin who created the behavior).
  11. Manipulate pixels using WriteableBitmap.  This can be used to create some very cool effects (some which may not be applicable to LOB applications…but they’re still cool).  I’m using it mainly to fill the printing hole mentioned below.
  12. Support for storing local data through isolated storage – By using isolated storage you can cache data, store data when no network connectivity is available plus more.
  13. Support for navigation – Silverlight 3 has a new navigation application template in Visual Studio that makes creating an application with multiple pages quite easy.  Each “page” can be linked to directly through deep linking and has built-in support for history.  If the client hits the back or forward button in the browser they’re taken to the appropriate Silverlight application page.  The navigation framework allows code to be placed into separate pages (or user controls) and then loaded as a particular link or menu item is clicked.  It’s a great feature that can really reduce the amount of code you have to write especially compared to Silverlight 2.

Silverlight 3 Cons

So everything’s all peachy right? Both the client and I are very happy with how things are going with the application but there have been some challenges along the way.  At the beginning of this post I said I’d mention the cons as well and I’m going to be brutally honest here with some of the areas where Silverlight 3 is missing the mark when it comes to Line of Business applications.

  1. No printing support.  Microsoft is working hard on this for future versions of Silverlight but if you can’t wait until then it’s definitely something to be aware of.  We knew about this going into the project so it was supposed to be a non issue since we could pop-up HTML overlays or open new browser windows that could be printed.  But, for one particular screen the lack of printing support is proving to be a challenge since it turns out the end user always prints the screen as they’re doing payroll work and the screen is quite complex.  I’ve come up with a work around using Silverlight 3’s WriteableBitmap but am currently sending bytes up to the server, converting them into a JPEG and then displaying the image in the browser.  Definitely a hack solution.  We’re now looking at generating dynamic Excel files on the fly at the client with a snapshot image of the Silverlight data since Excel will print the image properly and the browser doesn’t (still researching this option). If that doesn’t work we’ll just use reporting services to generate the same screen…not my preference though.
  2. Binding data to controls such as a ComboBox that is nested in other controls is harder than it should be.  I use a lot of ComboBox controls that are nested in DataGrid or ListBox rows in the application.  While I have it working fine now (after beating my head against the monitor a few times), the ComboBox control itself really needs a SelectedValue and ValueMember property for some situations and a way to more easily bind its ItemsSource to collections that may be defined outside of the current DataContext. All of this can be done via code but if you want to handle the majority of it declaratively in XAML it can be challenging in some cases especially once you start breaking parts of a page into user controls.  I ended up enhancing some code Rocky Lhotka blogged about and created my own ComboBox control that simplifies things a lot.
  3. Lack of built-in support for commanding.  What’s “commanding”?  In a nutshell it’s the ability to call a method within an object directly from XAML as an event fires instead of going through a code-behind file.  For example, when a button is clicked the click event can call directly into a ViewModel object that acts on the event.  By using commanding you can make your applications more testable. Frameworks such as Prism (and many others that have popped up) support simple button commanding and provide a code framework that can be used to build other types of commands.  The application I’m working on handles just about every event in the book (click, mouseenter, mouseleave, rowloaded, lostfocus, gotfocus, plus others) though and writing custom code just to handle events got old (so we simplified things and handle the event in the code-behind which notifies the ViewModel via events).  If you want to handle events directly in the code-behind file this is a non-issue for you, but if you want to handle them in another class it can be more challenging than it should be.
  4. Learning curve – There is certainly a learning curve associated with building Silverlight applications especially if you’re coming from building standard Web applications.  However, I think that’s the case with any technology.  I had already built several demo applications with Silverlight, co-authored a book and several articles on it and still ran into a few challenges with architecture choices along the way (we’re following the MVVM pattern).  I think it boils down to experience though so I list this one simply so that people know they will spend some time learning.  If you’re one of those people who doesn’t like to learn new things then Silverlight probably isn’t for you.  If you enjoy learning new things then I think you’ll love Silverlight once you get the hang of it.
  5. No built-in support for displaying Reporting Services reports within Silverlight – This isn’t a huge issue in my opinion since a report can be brought up in a separate browser window or displayed using an HTML overlay.  However, if you need to display the report directly in Silverlight there isn’t any built-in way to do that in Silverlight 3.  3rd party vendors to the rescue though.  Perpetuum Software now has a product that can integrate reports directly into Silverlight.
  6. The client has to have the Silverlight plugin installed.  I personally don’t view this as much of a con for internal enterprise LOB applications since it’s fairly easy for a PC manager to push out Silverlight to client PCs in many environments.  If the application will be run externally then installation of the plugin on each client has to be considered though.
  7. Sharing service types between proxy objects needs to be enhanced – When the project was initially started I wanted to use ADO.NET Data Services for some things and WCF for others.  The problem is that if both types of services reference the same type (such as Customer) then both generated proxy objects will contain a copy of that type which ultimately bloats the XAP size and leads to having to reference types by namespace down in the code versus a using statement at the top.  Although proxies can share code libraries from other projects (that's an option in the proxy generation wizard), my Model entities use .NET language features not available in Silverlight class libraries so type sharing won't work there.  It's something to keep in mind as you decide how you'll get data into your application.

There are definitely more pros than I’ve listed and probably a few more cons although I honestly can’t think of many more that I’ve had to deal with.  The bottom line is that all of the pieces are there (aside from printing) to build powerful Line of Business applications that are built using existing .NET languages.  You can make the applications look however you’d like and not have to worry if they’ll look good across different browsers.  Here’s a picture of a payroll screen in the early stages of development:

Makeover

Here’s what the screen looks like after applying a few styles to the controls and adding support for things like inline editing of data:

image

Some of the more “fun” features in Silverlight 3 can also be put to good use in Line of Business applications.  I needed to create a way for warehouse managers to easily manage multiple time cards for employees.  I ended up going with what I call a “card flow” interface (similar to cover flow in iTunes) to display the time cards.  The end user can use the mouse wheel to quickly navigate through different cards.  The selected card will slide to the middle with a cool animation and the others are angled using perspective 3D.  Here’s what the “card flow” interface looks like (I need to give credit to Jose Fajardo for blogging about the concept):

image

 

To Wrap It Up

So is Silverlight 3 ready for prime time, enterprise level Line of Business applications?  Having worked with the framework nearly every day for the past 3 months in a “real world” scenario my short answer is a big “YES”!  I don’t say this because I’ve been drinking the Kool-Aid though.  Anyone who knows me understands that I use what I feel works best for a given application (unless the client wants something specific of course).  I truly enjoy working with the framework and think it can do a lot of powerful things.

Every company is unique though so the answer really depends on what features your application needs.  Our previous client’s application was built using ASP.NET MVC and jQuery and it did everything they wanted it to do (I really like ASP.NET MVC and jQuery by the way).  However, Silverlight provides a more consistent way to develop enterprise applications that doesn’t require learning JavaScript, additional libraries like jQuery, CSS, HTML and other Web technologies.  With Silverlight you can write code using your favorite .NET language on both the client and server, debug applications like any normal .NET application, bind data in flexible ways, retrieve data from remote services, animate objects as needed, round corners and work with gradients without ever creating a .gif, .jpg or .png and have a ton of controls right at your finger tips.  I’m a big fan.

Logo

For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit www.thewahlingroup.com.

So What’s a Silverlight Value Converter Anyway?

Silverlight has an excellent data binding engine that allows data to be bound through XAML or programmatically with code.  My number one reason for using Silverlight on client projects is the data binding support.  Once you get into it and understand how it works it can save a lot of time when building applications.

When you’re binding data to controls there will be times when the data needs to be modified or tweaked some on the way into a control or as the data leaves a control and goes back to the source property (during a TwoWay binding for example).  Sure, you can always write code to change a given value, but in many cases it’s much easier to write a simple value converter instead that can be re-used.  In this post I’ll walk through creating a value converter and then show the code for a few of the value converters I find myself using fairly frequently.

Creating a Value Converter

Let’s look at a simple example of creating a value converter to get started.  Many applications work with DateTime objects but don’t want the time displayed or want the date formatted a specific way.  If you bind a DateTime property to something like a TextBlock in Silverlight you’ll get the standard output based upon the current culture:

clip_image002[11]

In the case of a birthday you want to show the date but don’t need the time of course.  You’d want something like the following:

clip_image002[13]

Although a separate property could be created in the source object being bound that handles formatting the date, a value converter can be created and re-used over and over anytime a specific date format needs to be created.  To create a value converter you’ll need to add a Silverlight class into your project and implement an interface named IValueConverter (located in the System.Windows.Data namespace).  This interface defines two members including Convert and ConvertBack. Convert is used to modify data as its bound from the source object to the control. ConvertBack works the other way. As a user changes data in a control such as a TextBox the data can be "converted back" to the original data type in the source object by using ConvertBack.

Both Convert and ConvertBack accept the same parameters including the data being bound, the type of the data being bound, any parameter data passed in that can be used in the data conversion process as well as the target culture that the entire process is running under (English, Spanish, French, etc.). Here’s what the method signatures look like:

object Convert(object value, Type targetType, object parameter, CultureInfo culture);
object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture);

Once IValueConverter is added to your class you can right-click it in Visual Studio and select Implement Interface from the menu to automatically fill in the Convert and ConvertBack methods. If you're using Visual Basic you can simply hit enter after the interface name to accomplish the same thing.  Here’s an example of a date value converter that allows dates to be formatted:

using System;
using System.Windows;
using System.Windows.Data;
using System.Globalization;

namespace View.Converters
{
   public class DateConverter : IValueConverter
    {

        #region IValueConverter Members

        //Called when binding from an object property to a control property
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null || (DateTime)value == DateTime.MinValue) return null;
            DateTime dt = (DateTime)value;
            return dt.ToString((string)parameter, culture);
        }

        //Called with two-way data binding as value is pulled out of control and put back into the property
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string val = (string)value;
            DateTime outDate;
            if (DateTime.TryParse(val, culture, DateTimeStyles.None, out outDate))
            {
                return outDate;
            }
            return DependencyProperty.UnsetValue;

        }

        #endregion
    }
}

To use a value converter you’ll need to first reference the class’s namespace (and assembly if the class is in a separate project).  This can be done in the XAML file where the value converter will be used, in App.xaml or in a merged resource dictionary file.  An example of defining a namespace in a resource dictionary file named Styles.xaml is shown next:

<ResourceDictionary
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:converters="clr-namespace:View.Converters"
>



</ResourceDictionary> 

Once the namespace is defined you need to define the converter using XAML and give it a key that can be used to reference the value converter (similar to an ID in ASP.NET):

<converters:DateConverter x:Key="DateConverter" />

Now that the converter is defined you can use it in any data binding that handles a DateTime object using the Binding object’s Converter and ConverterParameter properties.  Looking at the code below you can see that the converter is referenced using the StaticResource keyword (since it’s defined as a resource within your Silverlight project) which locates the appropriate key for the converter.

<TextBox x:Name="txtBirthday"
         Text="{Binding Birthday, Mode=TwoWay, Converter={StaticResource DateConverter},ConverterParameter=d}"
         FontFamily="Arial"
         Width="200"
         Height="20"
         Margin="5"  />

This automatically routes all in and out data binding operations (since it’s a TwoWay binding) through the value converter.  If data is being bound to a control such as a TextBox the parameter passed (“d” in this example) is used to format the DateTime object data.  If data is updated in the control it’ll automatically be converted from a string back into a DateTime object.

Value Converter Examples

I have quite a few value converters that I use from time to time in client applications and have listed some of them below.  If you have a favorite one you’re willing to share with others please add a comment to this post with your name, a description of the value converter as well as the code and I’ll update the blog (and give you credit of course) so that a nice library of value converters built-up over time. Update: Shawn Wildermuth let me know that the Silverlight Contrib project has some similar value converters as well as others so check that out as well if you get a chance.

BoolToVisibilityConverter

Handles converting boolean values into Visibility enumeration values.  This is useful when controls need to be shown and hidden based upon the value of a boolean property.  The Inverse parameter value can be passed when you want to hide a control when the property being bound is true or show the control when the value is false.

using System;
using System.Windows;
using System.Windows.Data;

namespace JobPlan.View.Converters
{
    public class BoolToVisibilityConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (parameter == null)
            {
                return ((bool)value == true) ? Visibility.Visible : Visibility.Collapsed;
            }
            else if (parameter.ToString() == "Inverse")
            {
                return ((bool)value == true) ? Visibility.Collapsed : Visibility.Visible;
            }
            return false;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}


DecimalFormatterConverter
 

Converts decimal values into different formats.

using System;
using System.Windows.Data;

namespace JobPlan.View.Converters
{
    public class DecimalFormatterConverter : IValueConverter
    {

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string format = (parameter == null) ? "#.##" : parameter.ToString();
            return (value == null) ? String.Empty : decimal.Parse(value.ToString()).ToString(format);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            try
            {
                if (value != null && value.ToString() != String.Empty)
                {
                    return decimal.Parse(value.ToString());
                }
            }
            catch { }
            return null;
        }

        #endregion
    }
}

ListCountVisibilityConverter

Handles showing and hiding controls such as ListBox based upon the number of items in the collection the control is bound to.  For example if there is only one item in a collection you may not want to show a ListBox control due to the data being shown with other controls in the UI.  You could pass a value of 1 for the ConverterParameter and the ListBox would automatically be hidden.

using System;
using System.Windows;
using System.Windows.Data;
using System.Collections;

namespace JobPlan.View.Converters
{
    public class ListCountVisibilityConverter : IValueConverter
    {

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null)
            {
                IList list = value as IList;
                if (list != null)
                {
                    int minCount = int.Parse(parameter.ToString());
                    return (list.Count > minCount) ? Visibility.Visible : Visibility.Collapsed;
                }

            }
            return Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}

NullToVisibilityConverter

Handles showing and hiding a control based upon a value being null or not.

using System;
using System.Windows;
using System.Windows.Data;

namespace JobPlan.View.Converters
{
    public class NullToVisibilityConverter : IValueConverter
    {

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (parameter == null) //Not invert parameter passed
            {
                return (value == null) ? Visibility.Collapsed : Visibility.Visible;
            }
            else if (parameter.ToString() == "Inverse")
            {
                return (value == null) ? Visibility.Visible : Visibility.Collapsed;
            }
            return Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}

StringTruncateConverter

Trims a string down to a specific length for display in the user interface.

using System;
using System.Windows.Data;

namespace JobPlan.View.Converters
{
    public class StringTruncateConverter : IValueConverter
    {

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            int maxLength;
            if (int.TryParse(parameter.ToString(), out maxLength))
            {
                string val = (value == null) ? null : value.ToString();
                if (val != null && val.Length > maxLength)
                {
                    return val.Substring(0, maxLength) + "..";
                }
            }
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}

Making Silverlight 3 Application Code More Compatible with Blend

Expression Blend 3 is a great tool for creating Silverlight or WPF user interfaces using design time tools and controls.  If you haven’t tried version 3 you’re really missing out since it adds a ton of new time-saving features.

While I really enjoy working in Blend, one of the things I’ve struggled with in the past is making code work better in Blend.  If you’ve ever had an error like the following you know what I mean:

image

What’s up with the error?  In short, I’m declaratively assigning my ViewModel object (my object that contains the data being bound to the Silverlight View if you’re new to the whole MVVM terminology) in the View’s resources area as shown next:

<navigation:Page.Resources>
    <viewModel:PayrollSummaryViewModel x:Key="ViewModel" />
</navigation:Page.Resources>

There’s nothing wrong with that except that when the ViewModel object’s constructor is called an error is occurring due to a null reference exception.  Note: Some people like the declarative way of defining ViewModels and some people don't.  A few months ago I was against that approach until I started working on my current project and realized that the pros outweighed the cons (at least for my scenario).  Plus, the declarative approach is used when working with test data in Blend 3.  Ultimately each application has different requirements so I'll leave it as an "exercise for the reader" to decide what works best for you.

Here’s the code in the constructor which is calling out to a WCF service to retrieve some data:

public PayrollSummaryViewModel(IServiceProxy proxy)
{
    _Proxy = (proxy != null) ? proxy : new ServiceProxy();
    GetPayrollSummary();
}

You obviously can’t call out to a WCF service when you don’t have access to an HTTP stack.  Fortunately, fixing the problem and making the code more “Blendable” is easy.  Silverlight has a class named DesignerProperties that can be used to check if the code is being run in a designer such as Blend or if the code is being run live.  Here’s an example of using the DesignerProperties class and wrapping it in a property named IsDesignTime:

public bool IsDesignTime
{
    get
    {
        return DesignerProperties.GetIsInDesignMode(Application.Current.RootVisual);
    }
}

To avoid trying to call the WCF service in the ViewModel object’s constructor when the code is run in Blend I can wrap the code with the call to IsDesignTime as shown next and Blend is happy with everything. 

public PayrollSummaryViewModel(IServiceProxy proxy)
{
    if (!this.IsDesignTime)
    {
        _Proxy = (proxy != null) ? proxy : new ServiceProxy();
        GetPayrollSummary();
    }
}

You can see that creating more “Blendable” code is pretty easy once you know this simple trick.  More info on the DesignerProperties class can be found here if you’re interested.  There are apparently some issues using it with the Visual Studio designer used for Silverlight 2, but since Silverlight 3 doesn’t have a Visual Studio designer that’s kind of a moot point.

Using Element to Element Binding for ToolTips in Silverlight 3

Silverlight 3 provides a new feature called “element to element” binding that allows one element to bind to another element’s property.  It’s really useful when you want to tie two objects together so that when one object changes the other changes as well.

A lot of the samples I see for this new technology tend to focus on using slider controls but I just don’t have a need for sliders most of the time (although it certainly depends upon what type of application you’re building).  Here’s a simple yet effective way to leverage element to element binding for tooltips.  I currently have a ComboBox control with a data template and want to show a description of the selected item as the user mouses over the control.  With Silverlight 2 you’d have to write code since there wouldn’t be a way for the tooltip service to bind to the selected item declaratively.  Now, you can do something like this (notice the ToolTipService attribute):

<ComboBox
    x:Name="WorkCodeComboBox"
    ItemsSource="{Binding Source={StaticResource ViewModel},Path=CurrentTimeSheetView.WorkCodes}"
    Style="{StaticResource TimeSheetComboBoxStyle}"
    SelectionChanged="WorkCode_SelectionChanged"
    ToolTipService.ToolTip="{Binding Path=SelectedItem.Description, ElementName=WorkCodeComboBox}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" Margin="0">
                <TextBlock Text="{Binding WorkCodeID}" Width="30" Margin="5,0,0,0" />
                <Rectangle Style="{StaticResource ComboBoxVerticalLine}" />
                <TextBlock Text="{Binding Description}" Width="250" Margin="10,0,0,0" />
            </StackPanel>
        </DataTemplate>
   </ComboBox.ItemTemplate>
</ComboBox>

In this case I’m binding the tooltip to the selected item’s Description property.  At first glance it looks like the ComboBox is binding to itself but in reality it’s binding to the ToolTipService’s Tooltip property.  A simple little trick but nice when you need it since it saves a line or two of C# code.

 

Logo

For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit www.thewahlingroup.com/.

WP Like Button Plugin by Free WordPress Templates