Archive for the ‘Tutorial’ Category.

New Silverlight Posts at Veracity Blogs

I’ve started a series of posts on Silverlight and other topics over at the Veracity Solutions Blog.

Veracity Solutions is the software consulting firm where I work and we’ve decided that it would be a good idea to do some sponsored posting there.

Blog posts up so far are:

More are coming, including tutorials on behaviors and paths.

Adventures with JSON and Silverlight (and the New York Times)

Summary: In this post, I walk through the basics of using Silverlight to query the New York Times Article API and display the results of the query. You can see the final result below.

You can also download source code for this project here.

JSON/Silverlight/New York Times project files

Huge thanks to Josh Holmes, whose JSON/Silverlight tutorial was the base of much of this project.

This project is somewhat code-intensive (and kind of long, expect 30-60 minutes), so if you just want the utility provided here without any of the work, you can skip over to my post on displaying the results, which is strictly a Blend tutorial.

However, I recommend walking through this one since it will help get you to a point of pulling real data from an API, which I’ve found to be a wonderful help as I practice putting together data-based designs. One of the things I’ve been wanting to be able to do as a designer is to explore a data set easily and quickly so that I can have data to play with in my interfaces. I found exactly what I wanted in the New York Times API, but then I found out I had to learn JSON.

“Oh great,” I said to myself, “another technology for me to learn.” But it turned out that I didn’t actually have to learn that much, because Visual Studio does nearly all the work for me.

Super Quick Introduction to JSON

If you’re not interested and you want to get to the business of grabbing New York Times data, you can skip it . It is helpful, but not strictly necessary.

JSON stands for JavaScript Object Notation and is basically just a really handy way to pass data along in a web service. It is very simple… within a set of curly brackets, you will have name/value pairs separated by a colon with each piece of data.
Example:
{
    FirstName : “Matthias”,
    LastName : “Shapiro”,
    Blog : “Designer WPF”
}

This is a JSON object. Arrays are created by using square brackets and JSON obejcts can be placed into a Javascript var. These things are not really related in anyway, but putting them in the same sentence allows me to only write one more example instead of two

Example:
{
    FirstName: “Matthias”,
    LastName: “Shapiro”,
    Siblings : [
    {Name : “Abby”},
    {Name : “Joel”},
    {Name : “Anna”},
    {Name : “John”},
    {Name : “Nate”}
    ]
}

And there we have the basics of JSON.

End of Super Quick Introduction to JSON

What is so awesome about JSON and Silverlight is that Visual Studio 2008 has a set of JSON-friendly classes that make working with JSON a breeze. Which is really handy because the New York Times, which is a dream come true for the new data-gatherer, delivers JSON results. So let’s walk through making a call to the New York Times Article API, handling the data we get back, and putting it into a Listbox for viewing.

First, go to the New York Times Developer site, log in (or register) and get your API key.

Next, start a new Silverlight project in Visual Studio 2008. I named mine “JSONNewYorkTimesTutorial”.

clip_image001[9]

Open your new project in Blend, pull up Page.xaml and add a TextBlock, ListBox, a TextBox and a Button. Name the ListBox “ResultsDisplay” and the TextBox “SearchText”.

clip_image001[13]

Now, my Page.xaml looks like this.

clip_image001[11]

OK… now let’s go to the code-behind for our project go to the event section of the button in Blend and type “PerformQuery” into the “Click” event.

clip_image001[15]

This will automatically insert the necessary code into the code-behind, so pull up Visual Studio. Before we implement a call to the NYT API, lets add some useful stuff. If you have not yet gone to get your Developer key, do so now.

private string myApiKey;
private WebClient callNYT;

public Page()
{
    InitializeComponent();
    myApiKey = “&api-key=(put your api key here. No, you may not have mine)”;
    callNYT = new WebClient();
    callNYT.OpenReadCompleted += new OpenReadCompletedEventHandler(callNYT_OpenReadCompleted);
}

In the code above, we’ve created a string that we can use to apply our unique NYT API key and we’ve created an instance of WebClient to call and receive information from the NYT API. When an object from the NYT API has been received , it will call the OpenReadCompleted event, which will be handled by our callNYT_OpenReadCompleted method.

(By the way, if you’re not getting the proper intellisense for the “Web Client” part, add “using System.Net;” to the top of your file.)

Now on to our button method. There are tons of things we can add to our query to find the exact information we want. But in the interest of simplicity, this post will deal only with a simple text search. To that end, let’s go to our PerformQuery method and turn it into this:

private void PerformQuery(object sender, RoutedEventArgs e)
{
    string NYTQueryBase = “http://api.nytimes.com/svc/search/v1/article”;
    string SearchTerm = “?query=”+ SearchText.Text;
    Uri queryUri = new Uri(NYTQueryBase + SearchTerm + myApiKey);

    callNYT.OpenReadAsync(queryUri);
}

We’ve done two things here. The first is that we built our search query using the query base, the query string and our API key. That was simple enough.

Next, we’ve going to use the WebClient we created to call our new query. When the query has been completed, our program will run the callNYT_OpenReadCompleted method with its result, which will be a JSON object constructed by the NYT servers. We will get back a JSON object with the following:

  • offset – We will get 10 results per page. The offset tells us which page of the results we’re on. The default is 0, which gives us results 0 – 9.
  • tokens – this is a array of our search terms.
  • total – this is an integer indicating of how many results there were for our search.
  • results – this is an array of results with the following format
    • body – a portion of the beginning of the article
    • byline – the article byline, usually including the author name
    • date – the date the article appeared, in a “yyyymmdd” format. For example, today would be “20090225”.
    • title – the article title
    • url – a url link to the article

A quick note: The NYT API is extremely flexible and we can actually define how we want our results to come back. This is just the default result format for the purposes of demonstration.

Before we handle this object, we want to create a class for the results. Right click on your project and go to “Add –> Class…”. Name your new class “NYTResult.cs” and make sure it looks like this:

public class NYTResult {
    public string Body { get; set; }
    public string Byline { get; set; }
    public DateTime Date { get; set; }
    public string Title { get; set; }
    public Uri Url { get; set; }
}

I added the following method to the class to handle the date conversion from the NYT format to a .NET DateTime object.

public DateTime formattedDateTime(string NYT_Time)
{
     int year = Convert.ToInt32(NYT_Time.Substring(0, 4));
    int month = Convert.ToInt32(NYT_Time.Substring(4, 2));
    int day = Convert.ToInt32(NYT_Time.Substring(6, 2));
    DateTime finalDateTime = new DateTime(year, month, day);
    return finalDateTime;
}

OK… now we’re really ready to handle the JSON object. Right click on the references in your project and select “Add Reference…”

clip_image001

In  your “Add References” box, select “System.Json” and click “OK”.

clip_image001[5]

Add “using System.Json;” to the references in your Page.xaml.cs file. And, just for good measure, add “using System.Collections.ObjectModel;” as well.

Go to the callNYT_OpenReadCompleted method and enter the following. I’ve tried to comment the code so that I don’t need to further explain it. Side note: I’m not always the best at understanding what is self-explanatory and what I need to elaborate on. If there are any additional questions, post them in the comments and I’ll answer as quickly as I can.

void callNYT_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    //grab our result and make a JSON Object out of it
    
//    then extract the results array from that object
    
JsonObject completeResult = (JsonObject)JsonObject.Load(e.Result);
    JsonArray resultsArray = (JsonArray)completeResult["results"];

    //an observable collection to hold the data and attach it to our ListBox

     ObservableCollection<NYTResult> resultCollection = new ObservableCollection<NYTResult>();

    //iterate through the results and transfer the data from a
    
//   JSON object into our nice pretty .NET object
    
foreach (JsonObject NYTRawResult in resultsArray)
    {
        NYTResult singleResult = new NYTResult();

        //don’t forget to check your results… an article might not have a
        
//  byline or a link
         if (NYTRawResult.Keys.Contains(“body”))
            singleResult.Body = NYTRawResult["body"];
        if(NYTRawResult.Keys.Contains(“byline”))
            singleResult.Byline = NYTRawResult["byline"];
        if (NYTRawResult.Keys.Contains(“date”))
            singleResult.Date = singleResult.formattedDateTime(NYTRawResult["date"]);
        if (NYTRawResult.Keys.Contains(“title”))
            singleResult.Title = NYTRawResult["title"];
        if (NYTRawResult.Keys.Contains(“url”))
            singleResult.Url = new Uri(NYTRawResult["url"]);

        //add our new result to the collection
        
resultCollection.Add(singleResult);
    }

    //assign the result as the source for our ListBox
    
ResultsDisplay.ItemsSource = resultCollection;

    //take the overall article count and display it
     resultCount.Text = “Number of articles: ” + completeResult["total"].ToString();
}

Now, we can run our project. Type something into the TextBox and hit the button and we get this:
clip_image001[7]

Not exactly the most readable thing ever. So let’s add the following to the ListBox XAML:

DisplayMemberPath=”Title”

Now we get something a little more like this (go ahead and give it a whirl):

Much better. Remember, this is a simple query, so it’s only looking for items that have that word in the article… it might not be in the title.

My next post builds on this one and I walk through building a more useful display for our results. It will be far less code intensive and far more designer centric.

I’ve made the source available for this project. I’ve taken out my NYT API key, so it will not run unless you get your own and put it in.

JSON – Silverlight – New York Times Tutorial Part 1 project files

Mask Animations (Clipping Path Animations) In Silverlight Without a Line of Code

Last night I submitted my MIX 10K Challenge piece, so I’m just killing time while I wait for it to get accepted. Please keep me in mind if you plan on voting.

OK… I’ve been excited about this for some time now. I found out (almost completely by accident) that you can animate a mask (also known as a clipping path) in Silverlight without writing code or even typing (much). This is exciting because I think it’s something that might interest our Flash friends who, late at night and in the privacy of their own homes, take a peek to see if Silverlight is worth looking into. When I worked with Flash, mask animations were my bread and butter and they seemed so hard to do in Silverlight.

But they’re not.

First open up your project in Blend. (I always create my project in Visual Studio and then open it in Blend because visual Studio has so much better project debugging and makes testing a breeze.)

Find the item you want to clip (in my case this is an image) and select the pen tool from the toolbar.

clip_image001

And start drawing.I’m a poor artist, so the star I drew looks pretty bad. If you need to change any of the points, use the direct selection tool (the light arrow, second from the top).

clip_image001[4]

OK… now the fun part. Add a storyboard to your project

clip_image001[6]

and you can animate the clipping mask using all the normal animation tools. Use the direct selection tool above to animate the vertices. You’ll get something like this:

Now… if you’re not interested in the details, just skip ahead a little bit. Something important happened the moment we started animating the path. Normally, path data is kept in a single string format that looks something like this:

Data=”M159.67175,104.26108 L177.91812,28.328932 L195.51648,104.43327 L255.0802,102.6104 L206.86984,151.82758 L225.8029,226.56477 L179.0616,179.17046 L129.73396,229.29906 L147.97842,150.63879 L98.650803,101.53297 z”

This is actually a “powerful and complex mini-language that that you can use to describe geometric paths in XAML.” Microsoft uses it by default to handle path data. But it doesn’t work very well for animating paths, so the second you animate a single vertex in your path, it changes the format you see above to the format you see below:

<Path.Data>
<PathGeometry>
<
PathFigure IsClosed=”True” StartPoint=”91.0527648925781,84.0121078491211″>
<
LineSegment Point=”118.057907104492,0.549586236476898″/>
<
LineSegment Point=”144.103973388672,84.2013778686523″/>
<
LineSegment Point=”232.259979248047,82.1977386474609″/>
<
LineSegment Point=”160.907287597656,136.2958984375″/>
<
LineSegment Point=”188.928756713867,218.444961547852″/>
<
LineSegment Point=”119.750289916992,166.350433349609″/>
<
LineSegment Point=”46.7439804077148,221.450408935547″/>
<
LineSegment Point=”73.7462997436523,134.989212036133″/>
<
LineSegment Point=”0.740016639232636,81.0134506225586″/>
</
PathFigure>
</
PathGeometry>
</
Path.Data>

Same data, but only this latter format is appropriate for animation. Remember this, it will come in handy in a second.

OK… now right click on your path and go to “Path –> Make Clipping Path”

clip_image001[10]

You’ll get a dialog pop-up that will ask you which item in the visual tree you would like to clip. I chose my image, but it will work with anything.

clip_image001[12]

And… poof! You have clipping animation.

LIMITATIONS: Here are the limitations to this method:

  1. You need to animate before you make your path into a clipping path. – Remember that little bit above about the data string format vs. path geometry? If you don’t animate before hand, Blend will convert all your beautiful line segments into the un-animate-able data string. Animating the path tells Blend to leave your formatting alone.
  2. Once you make your path a clipping  path, animation gets a lot harder – Basically, you can change the time by dragging the key frames around and change the easing. Any other alterations require entering values by hand. So do all your animation first before setting the path. The easiest work around to this is to copy and paste your path out of the Control.Clip section and back into your main XAML and tweak animation from there. But your best option is to just take the time to make your clipping animation perfect before you make it a clipping path.

How To Give a Silverlight 2 Gadget a Transparent Background

Warning: This is a poor solution if your gadget has any level of dragging interaction in it. The “windowless=true” step will make it so that any dragging interaction will be interrupted by the gadget, which will interpret such a move as an attempt to drag the gadget off the side bar.

Giving your Silverlight gadget a transparent background is actually quite simple. First, follow the directions from Chris Szurgot’s post on Silverlight gadgets. No point in duplicating his work.

When you’re done, create a transparent png file. Or download this one.

Now, head over to your html file. Get rid of all CSS background information. Add the following just below the body tag:

<g:background id=”background”
src=”transparent.png”
style=”position:absolute;top:0;left:0;z-index:-999;no=repeat; />

Finally, change the following params in the Silverlight object host.

<param name=”background” value=”transparent” />
<
param name=”windowless” value=”true” />

And that’s it.

Additional Warning: It looks like there is no solution yet for the pink halo around any anti-aliased pixels in a Silverlight gadget.

clip_image001

clip_image001[4]

This is a problem that transparent Silverlight gadgets have had for some time now. If that doesn’t bother you then you’re all set.

Getting a MouseLeftButtonDown or MouseLeftButtonUp Event From Your TextBox

One of the nifty little tricks I got working in my attempt to update my Silverlight Color Picker was that I wanted to have the entire content of a TextBox to select when I clicked on it. Imagine my surprise when clicking on the TextBox didn’t fire either a MouseLeftButtonUp or a MouseLeftButtonDown event!

This stunned me a little bit. Turns out there is a big discussion about this over at the Silverlight Forum. Long story short, I needed to add this code to my project (you’ll see it in my Color Picker project if you download it).

Add this code to your MyPage.xaml.cs file:

public class TextBoxClickable : TextBox
{
     protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
     {
           base.OnMouseLeftButtonDown(e);
           e.Handled = false;
     }

     protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
     {
           base.OnMouseLeftButtonUp(e);
           e.Handled = false;
     }
}

Your XAML should define your namespace:

<UserControl x:Class=”MyProjectName.MyPage
      xmlns:clickable=”clr-namespace:MyPage“>

And you can use your new clickable TextBox like this:

<clickable:TextBoxClickable MouseLeftButtonDown=”TextBox_SelectAll/>

If you’re like me and want to select everything in the TextBox with a single click, your method will look like this:

private void TextBox_SelectAll(object sender, MouseButtonEventArgs e)
{
     TextBox selectionBox = (TextBox)sender;
     selectionBox.SelectAll();
}

That’s it. I’ll post my updated color pickers in a couple hours.

How To Use a ListView or DataGrid In a ComboBox Drop Down (Without A Line Of Code)

Super cool new thing I learned today. In WPF, we can make it so that the drop down (popup) on a ComboBox displays the data in a ListView. Because of the fact that I believe the DataGrid will eventually overtake the ListView as the gold standard for data display in WPF, we’ll do it both ways.

This tutorial is done entirely in Blend and without a line of code.

Step 0) (for the DataGrid only)

Go to Code Plex and download the WPF Toolkit. Extract to a convenient location.

Right-Click on the References folder in your project tab and click “Add Reference…”

clip_image001

Navigate to the location you extracted the WPFToolkit.dll file, select it and hit OK.
clip_image001[6]

Step 1) Select the ComboBox you wish to change and edit the ControlTemplate by right-clicking and selecting “Edit Control Parts (Template) –> Edit a Copy…”

clip_image001[1]

Step 2) Find the ItemsPresenter. This is what would normally display our ItemsSource.

clip_image001[3]

We’re going to get rid of it. And the ScrollViewer for good measure.

Step 3) Where the ScrollViewer is, put in a ListView or a DataGrid, whichever one you’re using.

clip_image001[5]

Now, go the properties of that ListView or DataGrid and click on the box to the right of “ItemsSource”

clip_image001[11]

and, in the resulting menu, select “Template Binding –> ItemsSource”.

clip_image001[7]

Set the DataContext of the ListView or DataGrid to the DataContext of the parent ComboBox using the same process.

And… you’re done! Open the ComboBox and you will see that you can select items in the ListView or DataGrid in the ComboBox dropdown and see those items change the selection of the ComboBox.

clip_image001[13]

You’ll notice that this is probably not yet an ideal solution. For example, when we select an item, the dropdown doesn’t automatically close. Your best bet is to use the SelectionChanged event to trigger some logic to close the ComboBox dropdown.

Create a Zooming Button Style In Silverlight Without Code

Download code for this sample (updated for RCW)

I was reading Mike Snow’s blog and he had a recent Silverlight tutorial on creating a Zooming toolbar. I looked at it and said to myself, “I think I can do that without code in Blend!” So here’s a tutorial on exactly that.

End product :

Big bonuses to this XAML-only method include:

  • Much smoother animation
  • Midway animation (if you fly over a button, it doesn’t need to animate all the way up before it starts to animate back down)
  • Really low overhead
  • Can be done and maintained entirely by a designer in Blend without any code

1) create a new Silverlight project in either Visual Studio 2008 or Blend 2.5.

2) In Blend, add a new folder for our images by right-clicking on the project and selecting “Add New Folder”

clip_image001

3) Pull in our images by right-clicking on our new folder and selecting “Add Existing Item…” Navigate to the images you want to use and select “OK” to bring them into the project.

clip_image001[4]

4) Create the button to which you want to add the image and then double-click it in the Obejcts and Timeline pane so that it has a yellow outline around it.

clip_image001[6]

5) Now, go to the image you want to insert (in the Project panel), right click on it and select “Insert”

clip_image001[8]

OK… so now we have a button with an image in it. Now it’s time to make the sucker zoom.

6) Right click on the button and select “Edit Control Parts (Template) -> Edit a Copy…”

clip_image001[10]

Name your custom Template and hit OK

clip_image001[12]

7) In the “States” pane, you see a set of “CommonStates” (Normal, MouseOver, Pressed, and Disabled). Click on the MouseOver state and a red box will surround your composition, indicating that any changes made will be changes to the “Mouse Over” state, not to the default control.

clip_image001[14]

Recording state:

clip_image001[16]

8] Click on the highest level item in the template (in my case, it is a “Grid”) and go to the “Transform” section in the “Properties” pane and select the “Scale” transformation tab. Change the X and Y scales to “1.5″

clip_image001[18]

If you run the project now, you’ll notice that we get a cool zoom in effect on the mouse over, but our zoom out when the mouse leaves the button is basically a snap back to the original size. Let’s fix that now.

9) Click on the the arrow icon in the MouseOver state in the States pane and select the “MouseOver -> Normal”

clip_image001[20]

In the “Transition Duration” box, type “.2″

clip_image001[24]

10) Extra Designer Happiness Bonus Step! – If you’d like to have a zoom effect that isn’t strictly linear, open up the timeline view with the button on the right hand of the state recording box (seen below).

clip_image001[26]

Click and drag the keyframe (the light gray oval below) to the point you want it. I put mine at .3 seconds.

clip_image001[28]

With the keyframe selected, you should see an “Easing” pane on the right. The default easing is linear (aka. no easing), but you can change the easing curve by just dragging the yellow dots. Here is the easing curve I’ve found works pretty well for my apps.

clip_image001[30]

That’s it. Now you can just assign this template to a button and you’ll have this zooming functionality all set up.rcw_zooming_button

Styling a Silverlight ScrollViewer (to Look Like a Mac ScrollViewer)

Mac Scroller Project Files Updated for RCW

Just because we’re working in Microsoft technologies doesn’t mean we can’t throw a bone to our Mac friends. After all, they are the people we love, our cousins and our neighbors, and that irritating guy who is dating our daughter and can’t seem to shut up about how awesome his Mac is even though he’ll be long out of his program in musical costume design before he ever pays off his laptop …

Issues? I don’t have issues. Why do you ask?

Anyway, since Silverlight is a semi-ubiquitous technology, it would be nice if we could cater to all platforms and not make anyone feel left out. And nothing makes people feel more left out than when they expect their application to work one way and it doesn’t.

So, here’s a picture of what we’re going for.

clip_image001

As far as I’m concerned (and therefore as far as this tutorial is concerned) the important stuff is to make sure that the incremental buttons (the arrow buttons in the bottom right) are in the right place. We can deal with the color later.

OK, so let create our ScrollViewer (I’ll be using Blend exclusively for this). I tossed a button in it and made it small so we can see both of the ScrollBars.

clip_image001[4]

Right click on the ScrollViewer in the “Objects and Timeline” section and go down to “Edit Control Parts (Template) -> Edit a Copy…”

clip_image001[6]

You should have something that looks like this:

clip_image001[8]

Let’s do the VerticalScrollBar first. Right click on it and go to “Edit Control Parts (Template) -> Edit a Copy…” Name it something memorable and you should get something like this:

clip_image001[12]

This is actually easier than it looks. The unnamed rectangles and the path lay down the basic visual backbone for the ScrollBar and the rest of it runs like this:
clip_image001[14]
VerticalSmallDecrease – The up button
VerticalLargeDecrease – The space between the up button and the VerticalThumb
clip_image001[16]
VerticalThumb – The interface element that allows the dragging interaction of the scrollbar
VerticalLargeIncrease – The space between the down button and the VerticalThumb
clip_image001[18]
VerticalSmallIncrease – The down button

The horizontal root in this template is strikingly similar.

So, let’s start by moving the VerticalSmallDecrease button down to the bottom above the VerticalSmallIncrease button. The magic here will happen in the VerticalRoot grid. (I highly recommend the Design/XAML split view for this one.) In the design view, our grid looks like this:

clip_image001[20]

Ugly. However, in the XAML, it looks like this:

<Grid.RowDefinitions>
<
RowDefinition Height=”Auto”/>
<RowDefinition Height=”Auto”/>
<
RowDefinition Height=”Auto”/>
<
RowDefinition Height=”*”/>
<
RowDefinition Height=”Auto”/>
</
Grid.RowDefinitions>
<
Grid.ColumnDefinitions>
<
ColumnDefinition/>
<
ColumnDefinition/>
</
Grid.ColumnDefinitions>

Much easier. For the purposes of maintaining a coherent structure, drag the VerticalSmallDecrease in Objects and Timeline pane until it is between the VerticalSmallIncrease and the VerticalLargeIncrease. Next, change the third RowDefinition to “*”. You can do this in the XAML or by clicking on the “Auto” iconimage until it becomes a “*” icon. image Change the fourth RowDefinition from “*” to “Auto”. When you do this, it won’t immediately act like an “Auto”. This is because Blend gives it an automatic “MinHeight” of whatever the current Height is. You can change that in the XAML (easiest move) or you can highlight that row by clicking just below the “Auto” icon until the row highlights in a semitransparent gray like so.

clip_image001[28]

You may need to zoom in to do this. Once highlighted, the properties of the Row will show up in the Properties tab on the right. Change the MinHeight to 0.

clip_image001[32]

Now we’ll need to change the Grid.Row properties of almost everything. Click on the items in the Objects and Timeline and change the Row property in the Layout section of the Properties tab like so:

VerticalLargeDecrease -> Row = 0
VerticalThumb -> Row = 1
VerticalLargeIncrease -> Row = 2
VerticalSmallDecrease -> Row = 3
VerticalSmallIncrease -> Row = 4

You’re done. With the Vertical part of the ScrollBar at least. You can do the same thing with the Horizontal part of it. Just move around the buttons, change the ColumnDefinitions and update the Column assignments. My best recommendation is to go back to the ScrollViewer template and assign your new ScrollBar template to the HorizontalScrollBar and then go back to editing the template from there.

clip_image001[34]

Later on…

After a bunch of color tweaking, I have a scroll viewer in silverlight that looks like this:

clip_image001[36]

I’m feeling OK with it. I’ve embedded what I have at this point below.

Styling the ScrollViewer

I recently got a comment asking if I could do something on creating a Blend-type ScollViewer styling. The only problem is that the ScrollViewer is a multi-post affair, which I’ll try to get completed in the next month or so. I’m going to go ahead and put up the basics here, much like my Styling the ComboBox and Styling the ListView posts.

In the meantime, I’m making available for download a Resource Dictionary with the Blend ScrollViewer style as I’ve approximated it. (You may have to right-click “Save As…” on that file since IE will do its darndest to open it up.) Just load the resource dictionary into your project and set

<ScrollViewer Template=”{DynamicResource BlendScrollTemplate}” />

Note: This is not the “real” Blend styles… just my rendition/approximation.

In the meantime, here’s the overview for the ScrollViewer. When you look at a template of the ScrollViewer (right-click on the ScrollViewer, got to “Edit Control Parts (Template) -> Edit a Copy…“) you should see something like this:

clip_image001[7]

If you want to change something about the main content area (highlighted below), you’re probably going after the PART_ScrollContentPresenter

clip_image001[11]

If you want to style the corner (highlighted below), look at changing the Corner Rectangle.

clip_image001[15]

If you want to style the HorizontalScrollBar and/or the VerticalScrollBar (highlighted below), you should right-click on either the PART_VerticalScrollBar or the PART_HorizontalScrollBar and go to “Edit Control Parts (Template) -> Edit a Copy…

clip_image001[13]

A point of note: Because of the way Blend works, it can be difficult to visually style a Vertical and Horizontal ScrollBar in the same Template. Don’t create another template. It’s a waste of time and will make your resources a pain to navigate. I’ll go over exactly what to do in a little bit.

The ScrollBar template should look something like this:

clip_image001[9]

If you want to style the ScrollBar thumbs (the bars you would drag to scroll, highlighted below), you’ll need to change the template for the “Thumb” in the PART_Track. Note: Unless you’re doing something really complex, you should only need to style the Thumb control one time. You don’t need different styles for the vertical and the horizontal.

clip_image001[17]

If you want to style the directional buttons (highlighted below), you will need to change the templates for the first and last “RepeatButton” controls (the ones that aren’t in the PART_Track) using the right-click -> Edit Control Parts (Template) -> Edit Template. (This template should already be copied into your resources.) Again, unless you’re doing something complex, you should only need to style this button one time.

clip_image001[19]

If you want to style the empty area that allows for fast scrolling, you will need to change the style for the two RepeatButtons in the PART_Track (DecreaseRepeatButton and IncreaseRepeatButton)using the right-click -> Edit Control Parts (Template) -> Edit Template. You should only need to do this one time and then apply that style/template across the all the instances of this button.

clip_image001[21]

Over the next couple weeks, I’ll try to put up posts going over how to style all of these into the Blend style. I’ll update this post pointing to the more in-depth tutorials as I go along. Until I get around to doing that, feel free to download the ResourceDictionary with the Blend styles in them.

How Do I Make a ListView or a ScrollViewer Left Handed?

Several months back, I was doing some work for a company that was using WPF for a stylus based application. One of the things that they found they needed was a scrollbar that could be used by left handed people who would have to cover the entire screen with their left hand in order to scroll a traditional scroll viewer.

The solution ended up being so easy in WPF that I thought I’d post it here.

I’m in a two-birds-one-stone mood, so we’ll do this for both the listview, which will also cover a more traditional scrollviewer. Let’s start with our ever friendly listview.

NormalListViewAt the very sight of this thing, with a stylus in hand, your average lefty is thinking to him or herself “I wonder if I can do my work upside down?” Let’s show them that we love and accept them just as they are.

The first thing we’re going to do is create a new template for this sucker, so right click on your listview and go to “Edit Control Parts (Template) -> Edit a Copy…

Lefty_EditControlParts

Now we’re looking at the standard listview template. Mine looks like this:

ListViewTemplateLet’s dig right into the ScrollViewer. If you’re doing this from the listview (like I am) then creating a template for the listview has already created a template for the scrollviewer. If you’re starting from a basic scrollviewer, you can pretty much start right here.

For the purposes of making this thing easy to work with in Blend, go ahead and set the HorizontalScrollBarVisibility and VerticalScrollBarVisibility to Visible.

 ScrollBar_Visibility

And then “Edit Control Parts (Template) -> Edit a Copy…” (or “Edit Control Parts (Template) -> Edit Template” if it is available).

We are now looking at the guts of the ScrollViewer Control.

ListView ScrollViewer will look like this:

ListViewScrollTemplateThe normal ScrollViewer will look like this:

 NormalScrollViewer

For our purposes, they’re functionally the same. It is actually a fairly simple control… basically just a Grid panel with the columns and rows set up like so:

<Grid.ColumnDefinitions>
      <ColumnDefinition Width=”*/>
      <ColumnDefinition Width=”Auto/>
</Grid.ColumnDefinitions>

<Grid.RowDefinitions>
      <RowDefinition Height=”*/>
      <RowDefinition Height=”Auto/>
</Grid.RowDefinitions>

The scrollBars are set up so that their visibility is tied to (duh) the visibility that is set on the control. But what this does is it means that when they are collapsed… they Grid reclaims the space that they were taking up.

Now… here’s the hilarious part… in order to make this ScrollViewer left handed, all you have to do is swap the Grid.Columns:

<Grid.ColumnDefinitions>
      <ColumnDefinition Width=”Auto/>
      <ColumnDefinition Width=”*/>
</Grid.ColumnDefinitions>

You’ve now switched the columns so that the left handed column is auto. Here’s a list of the Grid.Column realignments you’ll need to make:

Change Column to “1″:

Lefty_Column1

  • PART_HorizontalScrollBar
  • All DockPanels (ListView only)
  • PART_ScrollContentPresenter (ScrollViewer only)
  • Corner (ScrollViewer only)

Change Column to “0″:

Lefty_Column0

  • PART_VerticalScrollBar

Basically, swap everything from in the two columns.

Done.

FinalLeftyListViewIf you want to make this a more robust control, I recommend creating a ScrollViewer with an additional dependency property (IsSouthPaw or something). Make it so that your Grid has three columns:

<Grid.ColumnDefinitions>
      <ColumnDefinition Width=”Auto/>
      <ColumnDefinition Width=”*/>
      <ColumnDefinition Width=”Auto/>

</Grid.ColumnDefinitions>

And then you can just create a trigger that swaps the column placement of your PART_VerticalScrollBar. Such a trigger will look something like this. And by “something”, I mean “exactly”.

<Trigger Property=”IsSouthPawValue=”True>
      <Setter Property=”Grid.ColumnTargetName=”PART_VerticalScrollBar“  Value=”0/>
</Trigger>

Go forth and make Ned Flanders proud.

By the way, I listen to pop punk whenever I write my tutorials and I just thought I should let Senses Fail know that they can probably get away with about 80% less “dying cat” screaming and still put out good music. You know… because they’re probably WPF programmers on the side and they’ll probably read this to solve all their left-handed scrollbar needs.