Archive for the ‘How To...’ Category.

Programmatic Paths and Buttons With Rounded Corners

I continue my stint blogging over at Veracity Blogs. New posts include:

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.

How To Create An Animated ScrollViewer (or ListBox) in WPF

UPDATED 05/22/09

In the comments, someone mentioned that the project wasn’t working properly for keyed scrolling. I’ve updated the project with:

  • Key scrolling (left, right, up, down, page up, page down)
  • CanKeyboardScroll property on the AnimatedScrollViewer so that keyboard scrolling can be turned off
  • ScrollToSelectedItem property on the AnimatedListBox so that the user can have it automatically scroll to a ListBoxItem

That last one is a little hacky… I use the ListBox ItemContainerGenerator to get the heights of all the items up to the one you want and then scroll it that. I’m almost positive there is a better way and if anyone knows what it is, I’d love to hear it.

First things first, here are the project files.

Animated ScrollViewer and ListBox Project Files (Updated 5/22/09) – Contains the AnimatedScrollViewer control library with AnimatedScrollViewer and AnimatedListBox

Animated ScrollViewer and ListBox DLL (Updated 5/22/09) – For those of you who don’t care how it works and just want it to work

OK… this is going to be something of a whirlwind since I’ve never written a post this in-depth before… it will strain the limits of my ADD.

Problem:

The Listbox/ScrollViewer not only doesn’t animate, but it seems impossible to tweak it so that it animates.

The Reason:

The reason has everything to do with the ScrollViewer. Basically, the ScrollContainer and the ScrollBars are very tightly intertwined. There is a lot of code that does all the scrolling calculations and that code needs to apply to the scrolled content as well as the UI for the ScrollBars. If you dig deep enough, you’ll see the reasons. Reasons which I assume for the moment you don’t care about… you’re probably in more of a “make the @#&($ thing work!” mood. I know I was.

The Solution:

My solution was basically to completely bypass the built-in ScrollBars and put in new ScrollBars with new logic. They look and act just like normal ScrollBars, so you should be able to style them just you would any normal ScrollViewer.

OK… how I did it. (I’m going to use both Blend 2 and Visual Studio 2008)

First, create a new custom control for WPF. This can be done by going into Visual Studio and creating a new Project. Select “WPF Custom Control Library”

clip_image001[7]

In Blend:

 clip_image001[9]

Add a WPF application to the project too so you have something to test. In the WPF application, get Blend to generate the default template for a normal ScrollViewer, accessible (in Blend) by putting a ScrollViewer into the project and right-clicking on it and selecting “Edit Control Parts (Template) –> Edit a Copy…”

clip_image001

Once have the default ScrollViewer template, select the “PART_VerticalScrollBar” and the “PART_HorizontalScrollBar” and copy and paste them. Rename your new ScrollBars something you like… I used “PART_AniVerticalScrollBar” and “PART"_AniHorizontalScrollBar”. Now, set the Visibility of the original ScrollBars to “Collapsed”. (We can’t get rid of them, because the ScrollViewer will be looking for them and will throw a conniption if it can’t find them.)

Also, change the Value of your new ScrollBars to 0. You’ll probably have to click on the orange box next to Value and select “Reset”.

clip_image001[11]

In Visual Studio, right-click on your WPF Custom Control project and go to “Add –> New Item…” . Then select “Custom Control (WPF)” and name it something you like (mine is named AnimatedScrollViewer). This should add a class to your project as well as a basic template to your Generic.xaml file.

Copy the ScrollViewer template that we just made and paste it into the Generic.xaml. The only change we need to make is to change:

TargetType="{x:Type ScrollViewer}"

to

TargetType="{x:Type local:AnimatedScrollViewer}"

in the Style and the ControlTemplate.

OK… that’s pretty much it with the XAML. Now we get to move into the code.

Right now, our class inherits from Control, but we want it to inherit from ScrollViewer like so:

public class AnimatedScrollViewer : ScrollViewer

Next get some containers for our new spiffy ScrollBars so that we can access them from the custom control code. Type the following before the class:

[TemplatePart(Name = "PART_AniVerticalScrollBar", Type = typeof(ScrollBar))]
[TemplatePart(Name = "PART_AniHorizontalScrollBar", Type = typeof(ScrollBar))]

and the following just inside the class:

ScrollBar _aniVerticalScrollBar;
ScrollBar _aniHorizontalScrollBar;

Now, we’ll override the OnApplyTemplate and make the connection between the template scrollBars and our class ScrollBars:

public override voidOnApplyTemplate()
{
    base.OnApplyTemplate();

    ScrollBar aniVScroll = base.GetTemplateChild("PART_AniVerticalScrollBar") asScrollBar;
    if(aniVScroll != null)
    {
        _aniVerticalScrollBar = aniVScroll;
    }
    _aniVerticalScrollBar.ValueChanged += newRoutedPropertyChangedEventHandler<double>(_aniVerticalScrollBar_ValueChanged);

    ScrollBar aniHScroll = base.GetTemplateChild("PART_AniHorizontalScrollBar") asScrollBar;
    if(aniHScroll != null)
    {
        _aniHorizontalScrollBar = aniHScroll;
    }
    _aniHorizontalScrollBar.ValueChanged += newRoutedPropertyChangedEventHandler<double>(_aniHorizontalScrollBar_ValueChanged);

    this.PreviewMouseWheel += newMouseWheelEventHandler(AnimatedScrollViewer_PreviewMouseWheel);
}

Before we address the three event handlers we added, we need to create the Dependency Properties with which they will be futzing.

(We’re going start going a little bit faster. Please download the code for the excruciating detail.) We need to add the following Dependency Properties. I’m using a “PropertyName (type)”.

Dependency Properties

ScrollingTime (TimeSpan) – This will be an easy way to change the speed of the scrolling. I created mine to default at half a second, but if you changed it to 0 seconds, it would act just like any normal ScrollViewer.

ScrollingSpline (KeySpline) – This property along with the ScrollingTime property is meant to give designers and developers the easiest control possible over the animation. This property describes the spline along which the scrolling will animate. If you don’t know what this means, just leave it alone, you’ll be fine.

TargetVerticalOffset (double) and TargetHorizontalOffset (double) – These are properties that tell the ScrollViewer where it will be animating to. In the PropertyChangedCallback, they kick off a method that starts the animation.

VerticalScrollOffset (double) and HorizontalScrollOffset (double) – For some reason the normal VerticalOffset and HorizontalOffset properties in a ScrollViewer are not capable of animation. So I wrote these properties that can be animated using standard storyboard procedures. If you use them to animate, make sure you also change the TargetVerticalOffset and TargetHorizontalOffset stuff as well… otherwise there will be a disconnect between the two.

Event Handlers

CustomPreviewMouseWheel event handler – This grabs any mouse wheel spinning and uses it to change the TargetVerticalOffset so that the ScrollViewer will still animate the scrolling when the mouse wheel spins.

VScrollBar_ValueChanged and HScrollBar_ValueChanged event handlers – These are called whenever the the ScrollBars are interacted with. There was a really weird problem with some of the interaction (the arrow keys and fast-scrolling buttons weren’t working properly), so these handlers hold logic to try to translate the weirdness into something viable. They then set the Target_Offset properties appropriately.

Methods

animateScroller – This method builds the animation programmatically based off of the appropriate properties and runs it.

And that’s really about it. Once you have the AnimatedScrollViewer working, you can just add use it inside your ListBox templates and it should work. (For those who are averse to doing such a thing, I’ve added extremely simple AnimatedListBox.)

INotifyPropertyChanged Snippets (And Why You Should Use These Instead of DependencyProperties)

First things first, here are my INotifyPropertyChanged snippets.

INotifyPropertyChanged snippet (PropertyChangedEventHandler and RaisePropertyChanged method)

INotifyPropertyChanged Property snippet

Just download them into your "Visual Studio 2008CodeSnippetsVisual C#My CodeSnippets" folder and they should work. Just type "notify" and intellisense should show you "notifyo" (for NotifyObject) and "notifyp" (for NotifyProperty). Hit tab twice and the code should dump into your project.

This is definitely a "use at your own risk" project.

You see, there I was, minding my own business and trying to build some data to use with some XAML comps I was playing with and I was having some of the strangest things happen with my data. I had a DependecyProperty ObservableCollection in my ViewModel and I put a couple different views in my screen. (I was using an MVVM pattern, because that’s what all the kool kids are doing.)

Then, it suddenly seemed as if all my Views were sharing the same ObservableCollection, even though every other DependencyProperty they were bound to had unique values. So I did what I always do when I have problems like this… I ask Joe McBride.

It turns out I had gotten confused. I understood that DependencyProperties were good for the following:

  • Providing callbacks when the property is changed
  • Binding to stuff
  • Animations

I figured that this is the kind of behavior I wanted from my data. I was wrong. As it turns out that is the kind of behavior I want out of the properties that I use in my WPF and Silverlight controls. It seems that DependencyProperties are meant to be used with controls and not for stand-alone data.

For stand-alone data, I should have used INotifyPropertyChanged, which is an interface for… well… notifying things when a property changes. I already had handy snippets for creating DependencyProperties (thanks to Robby Ingebretsen). So I tweaked his snippets so that they work for INotifyPropertyChanged properties.

Because it seems silly to implement the PropertyChangedEventHandler in every class that needs notify-able properties, I like to create a "NotifyObject" class:

class NotifyObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if(handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }       
}

Then, I can make my new class inherit from NotifyObject and away I go creating my bindable, notify-able data:

public class MyNotifyableData : NotifyObject
{
    public MyNotifyableData()
    {
    }

    #region MyProperty (INotifyPropertyChanged Property)
    private string _myProperty;

    public string MyProperty
    {
        get { return _myProperty; }
        set
       
{
            _myProperty = value;
            RaisePropertyChanged("MyProperty");
        }
    }
    #endregion
}

This property was created using my snippet above. Hope it helps.

Using the "Tag" Field And Triggers To Avoid Writing a Value Converter in WPF

I was working on a project recently and I wanted one of my layout controls to have a different margin based on a certain piece of data.

(It’s a long story… let’s just say that this is a good post if you want to change properties of a control based on a piece of data of a different type.)

So… for the sake of the argument, let’s say that I want my control to have a margin of “4,4,4,4″ if my data returns “dog” and I want it to have a margin of “2,2,2,2″ if my data returns “cat” and a margin of “0,0,0,0″ if the data is anything else.

Normally, I would use a value converter for this. My problem was that I was sick of using value converters for things so specific and using them only a couple times in my application. So I decided I wanted to do this one with styles and triggers.

First thing I did was bind my data to the “Tag” field.

<Border Style=”{DynamicResource MyBorderWithTriggers}” Tag=”{Binding MySpecialData}” >

Then, I created a style for my Border layout control. If you’re in Blend, go to Object –> Edit Style –> Create Empty…

clip_image001

Create a new property trigger by clicking on the “+ Property” button and change the property to “Tag”.

clip_image001[5]

I couldn’t find a way to type “dog” into the field value, so I did it in the XAML (full XAML sample below, for those of you who want to cut to the chase… you know who you are).

With the property trigger highlighted, you’ll see a “Trigger recording is on” sign in the corner of your canvas.

clip_image001[7]

Just change all the properties you want. Of course, in this case, I’m just going to change the Margin property. If we do the same thing for the “Cat” contingency, we get the following style.

<Style x:Key=”MyBorderWithTriggers” TargetType=”{x:Type Border}”>
        <
Setter Property=”Margin” Value=”0,0,0,0″/>        <Style.Triggers>
                <Trigger Property=”Tag” Value=”Dog”>
                        <Setter Property=”Margin” Value=”4,4,4,4″/>
                </Trigger>
                <Trigger Property=”Tag” Value=”Cat”>
                        <Setter Property=”Margin” Value=”2,2,2,2″/>
                </Trigger>
        </Style.Triggers>
</
Style>

And we end up with a layout that changes its properties based on a bound value. And we don’t have to write endless value converters.  Pretty handy… or at least I thought so.

Using Silverlight to Display JSON Data (Collected From The New York Times API)

In this post, you’ll either need to walk through this tutorial on how to call and prepare JSON data gathered from the New York Times API or, if you’re not particularly interested in doing that, you can just download the final project here. This tutorial pretty much assumes that you’re starting from the end of that tutorial.

Fortunately for everyone involved (especially me), this tutorial is much shorter. It is also another in my “without a line of code” series in which you can do everything without even touching the code. Let’s open up our project in Blend and get started. (To see an example what this tutorial makes, scroll to the bottom of this post.)

First of all, I lied. You do have to touch one line of code because you need to get your NYT API key and plug it into the myApiKey variable in the Page constructor (line 26 in the project available for download). The line should look like this:

myApiKey = “&api-key=your_api_key_here”;

Now, right click on the project solution and select “Build Solution” (in Visual Studio or Blend, it doesn’t matter).

clip_image001

This should build the assemblies so that Blend can do a really neat trick. In the Project tab in Blend, you should see a Data panel in the bottom half. Click on the “+ CLR Object” button.

clip_image001[5]

A pop-up will gently encourage you to name your new data source and choose from a list of available data sources. Select “NYTResult” and hit OK.

clip_image001[7]

You will now have your NYTResult data source show up in your Data pane. Before we start building a nice slick looking interface, select your ListBox (named “ResultsDisplay”) and, in the Properties pane, find the “Display Member Path” and reset it by clicking on the little gray box to the right.

clip_image001[13]

Now, right-click on the ListBox  in your “Objects and Timeline” panel and select “Bind ItemsSource to Data…”

clip_image001[9]

Select the data source you just created and select “NYTResult”. Then click on “Define DataTemplate” at the bottom. This will take you to the “Create Data Template” panel, where the fun happens. You will see “New Data Template and Display Fields” automatically selected. We like this. This lets us select all the data we want and give it some basic structure and Blend will do all the bindings for us.

Let’s make a few changes from the standard Data Template setup. Expand the Date field and check Day, DayOfWeek, Month, and Year and change the order with the up and down buttons to something you like. Then, change the Url from “StackPanel” to “TextBlock”. I reordered the data a little bit, so my template looks like this:

clip_image001[15]

Hit OK. The point of that whole exercise was so that Blend would build our data template for us. We don’t actually want the data source and we don’t want our ListBox bound to it. So reset the “ItemSource” property on the ListBox and remove the NYTResult data source. If you run the project now, you should get something like this:

clip_image001[17]

At least we’re getting more data now. Doesn’t look that great, but we’re getting there. Go back to your project in Blend and right-click on your ListBox and go to “Edit Other Templates –> Edit Generated Items (ItemTemplate) –> Edit Template”

clip_image001[19]

We’re now in the DataTemplate but we sadly have no visible data, which makes manipulating it a tad difficult. What I have found works best for me is just to build my desired layout with static data and then translate the bindings. (I haven’t mentioned this, but you should be working in Split mode as a general rule, so you should be able to see the bindings in the XAML.)

So… long story short (it’s getting really late here): I changed the layout to replicate the NYT story design… the Title is a hyperlink button that takes us to the full story, followed by a small byline, the beginning of the story and the date on which the story appeared. If you’d like to look at the design itself in more detail, download the project at the end of this post.

I do want to mention one issue… the issue of getting your text to wrap. With my current redesigned DataTemplate, my project looks like this:

clip_image001[21]

It scrolls horizontally to a degree that is certainly unhealthy. What is happening is that the TextBlock in the DataTemplate is making a request for space and when it hits a limit, it will start wrapping. Unfortunately for us, when the ScrollViewer in the ListBox has the HorizontalScrollBarVisibility set to “Auto”, it is telling the TextBlock that it has all the room in the world and that it doesn’t need to wrap. So, let’s just change the HorizontalScrollBarVisibility on the ListBox to “Disabled”.

And we’re done.

You can download the source here

JSON – Silverlight – New York Times Tutorial (Part 2) Project Files

Questions and comments are always welcome.

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.

Swapping Content In the Code Behind in Silverlight

I fought with this for a while today, so I thought I would toss it up as a solution.

I was trying to create a transition between two screens for a project I’m working on. I created the two ContentControls in my XAML like so:

<ContentControl x:Name=”OldContent”>
     
<!– My Old Content –>
</ContentControl>
<
ContentControl x:Name=”NewContent” Opacity=”0″>
     
<!– My New Content –>
</ContentControl>

Let’s say for the sake of this post that I was trying to animate the top content as a fade in and then, after the animation is done,  put the top content into the bottom content so that I could fill the NewContent with something else and have it ready for the next transition.

So… I’m using the following animation.

<Storyboard x:Name=”TransitionContent”>
   <
DoubleAnimationUsingKeyFrames BeginTime=”00:00:00″
         Storyboard.TargetName=”NewContent”
         Storyboard.TargetProperty=”Opacity”>
                <
SplineDoubleKeyFrame KeyTime=”00:00:00.03″ Value=”1″ />
   </DoubleAnimationUsingKeyFrames>
</
Storyboard>

(No Blend stuff today because I’m going a mile a minute for the sake of my looming project deadline.)

I add a “Completed” event handler to my Storyboard so that I can swap the content when the animation is over.

<Storyboard x:Name=”TransitionContent” Completed=”TransitionContent_Completed”>

In the C# code behind, I first wrote my content swapping like this:

this.OldContent.Content = this.NewContent.Content;
this.NewContent.Content = null;

And I got the following exception:

“System.ArgumentException was unhandled by user code
      Value does not fall within the expected range.”

I’m putting this in because it took me quite some time to figure out what the problem was. Simply put… Silverlight was yelling at me because I was trying to put the same stuff in the visual tree twice. This would have meant two copies of anything with a x:Name attribute… which would have been made it really hard for me to find anything. So it threw an exception.

Ultimately, I had to create an object to store the value of the NewContent  and then trash the NewContent.Content before I could put it into the OldContent.Content. I’ve re-written the code in such a way that if you wanted to swap the two contents, it will do just that.

private void Storyboard2_Completed(object sender, EventArgs e)       
{
            object oldStuff = this.OldContent.Content as object;
            object newStuff = this.NewContent.Content as object;

            this.OldContent.Content = null;
            this.NewContent.Content = null;

            this.OldContent.Content = newStuff;
            this.NewContent.Content = oldStuff;

            this.NewContent.Opacity = 0;
}

That last little bit is to reset the NewContent so that it is ready for the next transition.

And that’s all there is to it.

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