Archive for the ‘Silverlight’ Category

Basic Windows Phone 7 Motion Design

2 Comments »

Click here if you don’t want to hear me complain about the Silverlight toolkit and you just want to get to the animations.

If you are like me, you’re working on Windows Phone 7 applications in your pajamas, subsisting on pork jerky and Coke Zero and dreaming of that one project that will make you richer than your wildest dreams while begging Dell to actually announce some kind of release date for the Dell Venue Pro.

But I suspect that we have less in common. In fact, the only thing we probably have in common is a desire to know how to actually replicate the Windows Phone 7 motion design.

That and our breathtaking good looks.

But back to the motion design. If you download the Silverlight Windows Phone toolkit source code, download and run it, you’ll see some animations that look kind of like the animations on the phone but not really. There are a couple of reasons for this.

Reason #1 – The easing functions have been placed on the wrong keyframes in the toolkit. They should be placed on the second keyframe, but they are on the first keyframe. This, of course, doesn’t make any sense since there is nothing to ease in the first keyframe, so I suspect it is some kind of transcription error.

Reason #2 – The easing function is an exponential one. Not a problem, pretty normal. But its exponent is 15. To give you a good idea of what that kind of “easing” looks like, here is the Blend representation of an exponent 15 easing:

image

It’s basically like cutting the animation time by two thirds. In contrast, here is the function with an exponent 5 easing:

image

Much ease-ier (get it?).


OK… enough about the Silverlight toolkit. You want to actually know how to write animations that approximate Windows Phone 7, right?

I currently have no phone, so I can’t study the animations in the closest detail (waiting for the Dell Venue Pro), but here is what I’ve gathered from the Silverlight toolkit and what I can see in the emulator:

“In” animations

When some UI component is appearing, we would use an “In” animation. “In” animations are a shade longer than “Out” animations. I assume this is to help the users’ eyes adjust to the new UI.

To the best of my knowledge, “In” animations:

  • are .35 seconds long
  • use exponential 5 easing

“Out” animations

When a UI component is exiting (either through navigation or due to the lack of need for it) we use an “Out” animation. Their shorter length leave the user with the impression of speed when they want to get to the next UI.

“Out” animations:

  • are .25 seconds long
  • use exponential 5 easing

OK… now on to some XAML:

Turnstile Animations:

This is when the screen-wide UI turns on its left-hand edge, such as when the user opens an application.

Turnstile Forward In

Turnstile Forward In
  1. <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty=”(UIElement.Projection).(PlaneProjection.RotationY)”>
  2. <EasingDoubleKeyFrame KeyTime=”0″ Value=”-80″ />
  3. <EasingDoubleKeyFrame KeyTime=”0:0:0.35″ Value=”0″>
  4. <EasingDoubleKeyFrame.EasingFunction>
  5. <ExponentialEase EasingMode=”EaseOut” Exponent=”5″/>
  6. </EasingDoubleKeyFrame.EasingFunction>
  7. </EasingDoubleKeyFrame>
  8. </DoubleAnimationUsingKeyFrames>

Turnstile Forward Out

Turnstile Forward Out
  1. <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty=”(UIElement.Projection).(PlaneProjection.RotationY)”>
  2. <EasingDoubleKeyFrame KeyTime=”0″ Value=”0″ />
  3. <EasingDoubleKeyFrame KeyTime=”0:0:0.25″ Value=”50″>
  4. <EasingDoubleKeyFrame.EasingFunction>
  5. <ExponentialEase EasingMode=”EaseIn” Exponent=”5″/>
  6. </EasingDoubleKeyFrame.EasingFunction>
  7. </EasingDoubleKeyFrame>
  8. </DoubleAnimationUsingKeyFrames>

Turnstile Backward In

Turnstile Backward In
  1. <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty=”(UIElement.Projection).(PlaneProjection.RotationY)”>
  2. <EasingDoubleKeyFrame KeyTime=”0″ Value=”50″ />
  3. <EasingDoubleKeyFrame KeyTime=”0:0:0.35″ Value=”0″>
  4. <EasingDoubleKeyFrame.EasingFunction>
  5. <ExponentialEase EasingMode=”EaseOut” Exponent=”5″/>
  6. </EasingDoubleKeyFrame.EasingFunction>
  7. </EasingDoubleKeyFrame>
  8. </DoubleAnimationUsingKeyFrames>

Turnstile Backward Out

Code Snippet
  1. <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty=”(UIElement.Projection).(PlaneProjection.RotationY)”>
  2. <EasingDoubleKeyFrame KeyTime=”0″ Value=”0″ />
  3. <EasingDoubleKeyFrame KeyTime=”0:0:0.25″ Value=”-80″>
  4. <EasingDoubleKeyFrame.EasingFunction>
  5. <ExponentialEase EasingMode=”EaseIn” Exponent=”5″/>
  6. </EasingDoubleKeyFrame.EasingFunction>
  7. </EasingDoubleKeyFrame>
  8. </DoubleAnimationUsingKeyFrames>

Slide Animations

We see these animations in things like creating new e-mails. They seem to be used when the user is doing some task that fits within the context of the screen they are already on. Slide animations use an opacity animation combined with a horizontal or vertical animation.

Slide animations use the same .25 seconds on animate out and .35 seconds on animate in and, according to the toolkit, the UI slides 200 pixels in whatever direction it is sliding.

Here is a sample Slide Up and Slide Down animation:

Slide Up Fade In animation

Slide Up Fade In
  1. <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty=”(UIElement.RenderTransform).(TranslateTransform.Y)”>
  2. <EasingDoubleKeyFrame KeyTime=”0″ Value=”200″ />
  3. <EasingDoubleKeyFrame KeyTime=”0:0:0.35″ Value=”0″>
  4. <EasingDoubleKeyFrame.EasingFunction>
  5. <ExponentialEase EasingMode=”EaseOut” Exponent=”5″/>
  6. </EasingDoubleKeyFrame.EasingFunction>
  7. </EasingDoubleKeyFrame>
  8. </DoubleAnimationUsingKeyFrames>
  9. <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty=”(UIElement.Opacity)”>
  10. <EasingDoubleKeyFrame KeyTime=”0″ Value=”0″ />
  11. <EasingDoubleKeyFrame KeyTime=”0:0:0.35″ Value=”1″>
  12. <EasingDoubleKeyFrame.EasingFunction>
  13. <ExponentialEase EasingMode=”EaseOut” Exponent=”5″/>
  14. </EasingDoubleKeyFrame.EasingFunction>
  15. </EasingDoubleKeyFrame>
  16. </DoubleAnimationUsingKeyFrames>

Slide Down Fade Our animation

Code Snippet
  1. <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty=”(UIElement.RenderTransform).(TranslateTransform.Y)”>
  2. <EasingDoubleKeyFrame KeyTime=”0″ Value=”0″ />
  3. <EasingDoubleKeyFrame KeyTime=”0:0:0.25″ Value=”200″>
  4. <EasingDoubleKeyFrame.EasingFunction>
  5. <ExponentialEase EasingMode=”EaseOut” Exponent=”5″/>
  6. </EasingDoubleKeyFrame.EasingFunction>
  7. </EasingDoubleKeyFrame>
  8. </DoubleAnimationUsingKeyFrames>
  9. <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty=”(UIElement.Opacity)”>
  10. <EasingDoubleKeyFrame KeyTime=”0″ Value=”1″ />
  11. <EasingDoubleKeyFrame KeyTime=”0:0:0.25″ Value=”0″>
  12. <EasingDoubleKeyFrame.EasingFunction>
  13. <ExponentialEase EasingMode=”EaseOut” Exponent=”5″/>
  14. </EasingDoubleKeyFrame.EasingFunction>
  15. </EasingDoubleKeyFrame>
  16. </DoubleAnimationUsingKeyFrames>

Coming soon… swivel animations and rotate animations… I’m not totally certain on what I’m seeing in the toolkit. It doesn’t seem to jive with what I’m seeing from the phone. I may wait a few days until I get a phone and can dissect the motion design a  little bit more closely.


PHP, MySQL, and Silverlight: The Complete Tutorial (Part 3)

14 Comments »

This is meant to be the one-stop-shop blog post for creating a very simple web service in PHP that pulls from a MySQL database and displaying the data in Silverlight. Emphasis on the “simple”. Here is an example of the finished product (I reserve the right to clean up the data on a regular basis):

Part 1: MySQL

Part 2: PHP

Download all files (PHP & Silverlight)
Download PHP files only
Download Silverlight project only

In Part 1, we created the MySQL tables necessary to store data for a simple to-do list. In Part 2, we wrote a PHP service to deliver the items in our to-do list in JSON format. In Part 3, we’ll create a Silverlight application that can utilize this web service to retrieve, display, and edit the to-do list.

Part 3: Connecting Silverlight To Our PHP Web Service

First, let’s start a new Silverlight project. (You can download the full project here.) In the interest of time, I’m not going to go into the details of the “ideal” implementation for this. I’m just going to show the parts necessary to retrieve, display and interact with the to-do data.

Before we start with the UI, let’s build a model so that we can appropriately bind our data. Add a new folder to the Silverlight project and name it “Models”. Add a new class to it and name the class “ToDoItem.cs”. In this instance, we’re just going to make the model look just like our MySQL table.

ToDoItem.cs

public class ToDoItem
{
public bool isDone { get; set; }
public string toDoDescription {get; set;}
public int toDoID {get; set;}

public
ToDoItem() { }
}

Now, we’ll add to our MainPage.xaml a ListBox named “ToDoList” that will hold the to-do items and a Grid to house the UI to add a new to-do. We’ll work on gathering and displaying our items first.

Right-click on the ListBox and go to “Edit Additional Templates –> Edit Generated Items (ItemTemplate) –> Create Empty…
clip_image001
You’ll love this part… Just add a checkbox to it. That’s all we’ll need, so that’s all we’ll add. Then, go into the XAML and make the checkbox look like this:

<CheckBox Content=”{Binding toDoDescription}”
IsChecked=”{Binding isDone}”
Tag=”{Binding toDoID}” />

This binding is all we’ll need once we gather our to-dos from the web service and attach it to the ListBox. Let’s go ahead and get that data into this ListBox.

Open MainPage.xaml.cs and, at the top of the class, add:

WebClient wc = new WebClient();
ObservableCollection<ToDoItem> myToDoList = new ObservableCollection<ToDoItem
>();
string baseURI = “http://<Web_address_holding_your_php_files>”;

You may have to add “using System.Net;” and “using System.Collections.ObjectModel;” to the top of the file. While we’re adding references, right-click on the “References” folder and find the “System.Json” component and add it to the project. Then add “using System.Json;” to the references section in the top. It’ll come in handy in a minute.

In the MainPage() method under InitializeComponent(), type “wc.DownloadStringCompleted += “ and hit TAB twice. This will add an event handler for when the WebClient has finished connecting to the web service we wrote.

The resulting event handler (which should be named “wc_DownloadStringCompleted”), is the code that our application will go to whenever it makes a call to our web service and gets a result. In it, we will do the following things:

  1. Check to make sure we got a result without error
  2. Check to see what kind of result we got (did we get all to-do items? or add a new to-do item?)
  3. Walk through the result, extracting the data we need
  4. Apply that data to the UI

Let’s add the code to do that for getting all the items. Make your event handler look like this:

wc_DownloadStringCompleted
  1. void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
  2. {
  3. if (e.Error == null && e.Result!= “”)
  4. {
  5. JsonValue completeResult = JsonPrimitive.Parse(e.Result);
  6. string resultType = completeResult["returnType"].ToString().Replace(‘”‘, ‘ ‘).Trim();
  7. if (resultType == “todoItems”)
  8. {
  9. myToDoList.Clear();
  10. JsonArray toDoItemsJson = (JsonArray)completeResult["results"];
  11. foreach (JsonValue todoItemJson in toDoItemsJson)
  12. {
  13. ToDoItem thisTodo = new ToDoItem();
  14. if (todoItemJson["ToDoIndex"] != null)
  15. thisTodo.toDoID = Convert.ToInt32(todoItemJson["ToDoIndex"].ToString().Replace(‘”‘, ‘ ‘).Trim());
  16. if (todoItemJson["TodoText"] != null)
  17. thisTodo.toDoDescription = todoItemJson["TodoText"].ToString().Replace(‘”‘, ‘ ‘).Trim();
  18. if (todoItemJson["IsDone"] != null)
  19. {
  20. int isDoneInt = Convert.ToInt32(todoItemJson["IsDone"].ToString().Replace(‘”‘, ‘ ‘).Trim());
  21. if(isDoneInt == 0){
  22. thisTodo.isDone = false;
  23. } else if (isDoneInt == 1){
  24. thisTodo.isDone = true;
  25. }
  26. }
  27. myToDoList.Add(thisTodo);
  28. }
  29. ToDoList.ItemsSource = myToDoList;
  30. }
  31. }
  32. }

With this in place, all we need to do is make a call to the get_todo_items.php, which we can do by adding this code just below the wc.DownloadStringCompleted line in the MainPage() method.

wc.DownloadStringAsync(new Uri(baseURI + “get_todo_items.php”));

When we run the project, we should get all objects from our database and the results should show up just the way we want in our Silverlight application. We will follow the exact same model to add new to-do items and update the to-do items we already have.

I’m in the process of separating out the final part of this tutorial (adding and updating the items) into a supplemental post so that I can wrap this post up. I encourage anyone walking through this to try to complete those parts by yourself and refer to the last bit only if you get stuck.

Finally, a little bit of warning. I structured this project to get it working in as straightforward a manner as possible. It is not in any way the ideal architectural example for a data-driven Silverlight application. It’s just a good way to get started using Silverlight in an environment that isn’t 100% Microsoft technologies.


PHP, MySQL, and Silverlight: The Complete Tutorial (Part 2)

6 Comments »

This is meant to be the one-stop-shop blog post for creating a very simple web service in PHP that pulls from a MySQL database and displaying the data in Silverlight. Emphasis on the “simple”.

Here is an example of the finished product (I reserve the right to clean up the data on a regular basis):

Part 1: MySQL

Part 3: Silverlight

Download all files (PHP & Silverlight)
Download PHP files only
Download Silverlight project only

In Part 1, we created the MySQL tables necessary to store data for a simple to-do list. In Part 2, we’ll write some PHP code that will give us the ability to grab the data out of the database and send it, in JSON format, to our Silverlight application.

Part 2: Writing the PHP Web Service

We’re going to create 4 PHP files (download php files):

  • mysql_vars.php – holds all the information for connecting to the MySQL database
  • get_todo_items.php – for getting all the to do items
  • add_todo_item.php – adds a to do item
  • change_status.php – changes a to-do item from “not done” to “done” or vice versa

Since all these projects will be using the information in mysql_vars.php, we’ll write that first.

mysql_vars.php

<?php
$dbUsername = “[my_database_username]“;
$dbPassword = “[my_database_password]“;
$db = “[my_database_name]“;
$server = “[my_database_server]“;

//To Do Table and Column Names
$mysql_todoTable  = “to_do_data“;
$mysql_todoIndexCol = “index_key“;
$mysql_isDoneCol = “is_done“;
$mysql_todoTextCol = “to_do_text“;

$connection = mysql_connect($server, $dbUsername, $dbPassword);

function formatInput($rawURLData)
{
$returnString = urldecode($rawURLData);
$returnString = mysql_real_escape_string($returnString);
return $returnString;
}
?>

We’ve added the to-do table and column names so that, if we decide to change anything later, we can just go to this file and update the table or column once.

Just for good measure, we’ve added a function we’ll want to use across our php files. The function “formatInput” will be used to make sure all our data is decoded from the URL that calls our web service (the urldecode method) and then try to block any SQL injections (the mysql_real_escape_string method).

Now, let’s write the basic “Get the data” file. What we’re going to do is write it so that the we can choose to get:

  • all the to-do items
  • all the to-do items that are “done”
  • all the to-do items that are “not done”

This range of functionality isn’t even close to ideal. In a perfect world, we would want a wider range of options in gathering items (for example, items that contain a certain word or one item in particular or limit the number of items we call by a date range). However, for our very simple purposes, this will do.

The way our web service will work is that we have a URL that we’ll call from Silverlight when we want to get some data. When we calls this web service, we may want only the “not done” items or only the “done” items. We’ll handle that option by adding “?itemStatus=done” or “?itemStatus=notDone” to the end of the URL.

Example: if our base URL is

http://www.mywebsite.com/

the call to

http://www.mywebsite.com/get_todo_items.php

will get all items, regardless of their completed status while

http://www.mywebsite.com/get_todo_items.php?itemStatus=done

will get all the to do items that are complete. So we need to make sure that our web service responds appropriately to both calls.

There are comments in the code, but I’ll just explain the basic concept in picture form:

We take in a URL, extract the variables from it, create the MySQL query based on the variables, execute the MySQL query, extract the results, and then send back the php object encoded as a Json object. Each one of our files will follow this same pattern.

get_todo_items.php

<?
include ‘mysql_vars.php’;

//    set up the “itemStatus” URL option and build a query addition
//        to account for the itemStatus variable
$itemStatus = $_GET['itemStatus'];
$itemQueryAddition = “”;

if($itemStatus != NULL)
{
if($itemStatus == “done”)
{
$itemQueryAddition = “WHERE `$mysql_isDoneCol` = 1″;
} else if ($itemStatus == “notDone”)
{
$itemQueryAddition = “WHERE `$mysql_isDoneCol` = 0″;
}

// Construct our MySQL query
$todoQuery = “SELECT * FROM `$mysql_todoTable` $itemQueryAddition ;”;

// execute the query and gather the results…
mysql_select_db($db, $connection);
$todoResult = mysql_query($todoQuery);
$todoArray = array();

while($itemRow = mysql_fetch_array($todoResult))
{
$todoArray[] = array( “ToDoIndex” => $itemRow['index_key'],
“IsDone” => $itemRow['is_done'],
“TodoText” => $itemRow['to_do_text'] );
}
mysql_close($connection);

// … then encode the results as JSON Text…
// we’re using a “returnType” field so that our Silverlight application can differentiate between
// the kind of return values it recieves and parse the Json object appropriately

$returnItems = array( “returnType” => “todoItems”,
“results” => $returnItems);
$JSONResult = json_encode($todoArray);

// … and print the results so that our app can read them
echo $JSONResult;
?>

The other two files, add_todo_item.php and change_status.php use exactly the same structure to add a new item and change the status of an existing item (respectively). I won’t put all the code here in this post that is already too long, but you can download all the files here.

Update the mysql_vars.php file to fit your needs and you should be able to just upload these files and have your running to-do web service all ready for Silverlight to call it for data, which is something we’ll deal with in Part 3.


PHP, MySQL and Silverlight: The Complete Tutorial (Part 1)

3 Comments »

This is meant to be the one-stop-shop blog post for creating a very simple web service in PHP that pulls from a MySQL database and displaying the data in Silverlight. Emphasis on the “simple”. This tutorial is geared toward someone who has never done databases or web services.

Here is an example of the finished product (I reserve the right to clean up the data on a regular basis):

This tutorial will walk through the steps to create a simple to-do list. Our to-do list will hold text of what it is we need to do and a value indicating if the task has been done. In this tutorial, we will create a MySQL table to hold our data, a PHP service to call the data and a Silverlight application to display and interact with the data.

Part 2: PHP

Part 3: Silverlight

Download all files (PHP & Silverlight)
Download PHP files only
Download Silverlight project only

Part 1: The MySQL Database

First, let’s create the table we need for our data.

If you don’t have or don’t like phpMyAdmin, the MySQL query to create the table described below is:

CREATE TABLE `[your_database_name]`.`to_do_data` (
`index_key` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`is_done` TINYINT( 4 ) NOT NULL DEFAULT ’0′,
`to_do_text` TEXT NOT NULL ,
FULLTEXT ( `to_do_text` )
) ENGINE = MYISAM

If you have phpMyAdmin, I highly suggest using it if you’re a MySQL novice. In phpMyAdmin, go to your database and enter the name of the table you want to create in the “Create new table on database [your_db_name]” section.

clip_image001[5]

We’ll call our table “to_do_data” and give it 3 fields.

  • index_key – identifies the to-do item uniquely
  • is_done  – true/false value indicates the status of the to-do item
  • to_do_text – a short text to describe what needs to be done

In phpMyAdmin, it will look like this:

clip_image001

A couple of notes about the fields:

index_key

This is the primary key of the table and is used to uniquely identify the given row. As such, it cannot be null and it auto-increments as rows are added to the table.

is_done

We use “TINYINT” type for this value because using BOOLEAN is basically the same thing. It is not null because every item must either be “done” or “not done”. “Done” = true = 1 and “not done” = false = 0. We are going to default to “0” (false) because we’re assuming that users aren’t going to make a to do list of stuff that is already complete.

to_do_text

We have artificially limited the text size to 1024 because we assume that this will be a set of short to-dos to, not a set of journal entries. We’ve also turned on “Fulltext” which lets the MySQL database index our entries for quick searching.

Now we just click the “Save” button at the bottom and we have our table.

clip_image001[7]

Now our database system is in place and we’re ready to write a PHP webservice to implement all the CRUD (create, read, update, delete) capabilities our system will need.

If you want to learn more about MySQL, I highly recommend “A Visual Introduction to SQL“. This is the book I have, a left-over of my grad school years and it is an exceptional book for picking your way through various database scenarios.

If you’re looking for something a bit less costly, “MySQL Crash Course” is a fine book on the subject as well.


Recovery Review: A Silverlight Sunlight Foundation Visualization Project

1 Comment »

If you’re interested in government transparency, there is not better organization to watch than the Sunlight Foundation, a non-profit organization that is leading the charge to more government transparency through the release, organization and visualization of government data and processes.

Every once in a while, Sunlight Foundation runs contests to either visualize or interact with government data. I submitted a Silverlight project called “Recovery Review” for the latest contest, “Design for America”. With Recovery Review, users can search and visualize stimulus projects. If they find information that they think is inaccurate, they can flag that project for inaccurate information.

clip_image001

The idea behind the visualization is that users can search through the data using a couple of key points (how much money was awarded to a project, where the project is, how many jobs were reported as “saved or created” due to the project, etc) and the system will deliver in a visual format a set of results that match that search. It will also visualize (as seen above) the total of all awards that match that search in the context of the stimulus awarded as a whole.

If the user clicks on the on one of the projects in the list, the visualization resizes so the user can see how much money and how many jobs that individual project represents, both in relation to the search total and in relation to the total stimulus.

clip_image001[14]

Here’s a video overview of the project (runs about 8 mins).

And here is a blog post for the project that discusses some of the design decisions made and what I would change given more time.

Looking at the competition, I find it unlikely that I will win, but building the project was a pretty exciting learning experience. I’ll be posting my lessons here in the next couple weeks.


Code for MIX10 Information Visualization Talk Demos

7 Comments »

As promised, I’m posting my code for the demos from my MIX10 “Creating Effective Information Visualization in Silverlight” talk.

Unemployment Data Demo Code

Bing Maps Twitter Demo Code

In case you want to take a look at the unemployment visualization, I’ve added it below. I’m looking for a place to do ASP.Net hosting because my Bing Maps visualization is driven using Twitter data called and served through a WCF service, so if you have a recommendation for a noob ASP.Net guy, let me know. I’d love to host that as well.

(Apparently some people are having trouble with my demo below. I’ll try to get a more compatible version up soon.)


Get Microsoft Silverlight

You can copy the code for to embed this with the text below:


Info Vis, Snapping Behaviors, Illustrator Guidance and Custom Control Stuff

No Comments »

I’ve been a busy blogger over at Veracity Blogs the last couple weeks. Here’s a list of my new posts:

  • Florida Crime Rate Visualization – My attempts to use Silverlight for information visualizations are going pretty well. In this post, I visualize the Florida crime rate by county over almost 20 years. There are project files availalbe for anyone who wants to dig into how I did it a little more.
  • Adobe Illustrator to XAML Conversion Options – This post walks through the pros and cons of two methods for taking an SVG file (or Adobe Illustrator) file and pulling it into Blend as a XAML file. It also has a XAML copy of a vector map of the US by county for download.
  • Create A Snapping Slider In Blend Using Behaviors – This provides a downloadable behavior for getting a slider to snap to integers (or an integer multiple based on certain settings). I’ve provided project files as well as a tutorial for how to do it.
  • How To Create a PART in Your Silverlight Custom Control – Because there are about a dozen tutorials on building a custom control, but I keep forgetting exactly how to do this part of it.
  • How To Animate a Changing Property in a Custom Control in Silverlight – Have you ever wanted your property to animation automatically when it changes in your Silverlight Custom Control. I say, “Who hasn’t!?” at which point my wife forces me out into the fresh air and sunshine (or, as I call it, the Blinding Day Star). After I scurry back inside, I wrote this blog post.
  • How To Build a Storyboard Animation for Silverlight in C# – Because sometimes you want to enjoy the benefits of the Silverlight animation engine but you really need to build the animation in the code instead of the XAML.

New Silverlight Posts at Veracity Blogs

No Comments »

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.


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

4 Comments »

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.


Source Code For Presidential Candidate Tracker Visualization

4 Comments »

Due to repeated requests for the source code (and the fact that I apparently can’t brag about it on Silverlight.Net without a link to the source code), I’m putting it up for download.

Presidential Candidate News Tracker Source Code

JSON Data File With Candidate Data (Note: Apparently, WordPress likes to uncapitalize file names for me, you may have to re-name the file to “CandData.json” to get it to work with the app.)

Warning: This code is a disaster. I was having strange problems getting my custom controls to work and, after a couple hours fighting with it, I gave up and ended up writing the exact same layout and code for 14 separate candidates. Same problem with the “dates-of-note” along the timeline.

Not pretty, but it works. Have fun.


Follow me: matthiasshapiro