Archive for the ‘WPF’ Category

Vote for my MIX 11 Open Call Session

No Comments »

One of the things that I’ve been fascinated by since last year’s MIX conference is the motion design in place in Windows Phone 7. In a past life I worked as a video producer and I’m always stunned to see how well people respond to beautiful animations… especially in interface design.

You can see this fascination in my multiple blog posts on Windows Phone 7 motion design:

Now I’m trying to take my passion and talk about it at MIX 11. My goal with this talk is to show some excellent examples of practical motion design and show 1) how users really respond to good motion design and how it helps our applications seem more responsive and 2) show how to practically implement this motion design in our applications.

My goal is to help us all see how motion design is not icing on the cake, but an essential part of building beautiful applications. So, if you could, please vote for me and help me speak at MIX 11.


XAML Files for Location Visualizations in Silverlight and WPF

No Comments »

In the comments of my Silverlight unemployment visualization, someone asked about where I got the US outline. I got it from the WikiCommons website which has an SVG (scalable vector graphics) version that I pulled into Adobe Illustrator and then exported as a XAML file using Mike Swanson’s Illustrator-to-XAML plugin.

I realized this might not be possible for many people who don’t own Adobe Illustrator, so I did it myself for several files that are now available for download as XAML vector graphics maps of the US.

Download all Silverlight and WPF XAML files

Silverlight

WPF

I’ll confess, the real difference between the Silverlight and WPF files is that the WPF files encapsulate everything into a “Viewbox” control that allows dynamic resizing of the maps. If you want that functionality in Silverlight, just download and install the Silverlight toolkit and encapsulate the Canvas into a Viewbox. (The Viewbox will be a standard control in Silverlight 4, I am reliably informed.)

Now, a quick overview of the files:

United States Map with States

This is a nice tidy file (69K) with vector maps for all the states in the US. Each state has been named by its abbreviation. For example, the California map path would have the attribute: x:Name=”CA”.

United States Map with Congressional Districts

This file is based off of the Wiki Commons Congressional District map and is pretty big (about 1 MB). The paths are named based on a State_District naming convention. For example: Washington’s 8th Congressional District would have the attribute x:Name=”WA_8″.

There are 7 “at large” districts, which indicate states that only have one congressional seat. They have the attribute “State_At_Large“… for example, North Dakota’s one and only congressional district has the attribute x:Name=”ND_At_Large”.

United States Map with Counties (FIPS)

This map is pretty hefty at 1.5 MB. All paths have a FIPS code for the county they represent as their x:Name attribute. A FIPS code is a 5 digit code corresponding to a unique county in the United States. The first two digits indicate a state (for example, California is “06″) and the last three digits indicate a unique county (for example, Orange County in California is “059″). Because of the limitations in the XAML x:Name conventions, the FIPS code for a county is preceeded by an underscore. So, the path indicating Orange County, California would be x:Name=”_06509″.

If you need a FIPS-to-CountyName file, check out this FIPS code CSV file.

United States Map with Counties (County Names)

This is the same map as the FIPS map except that the x:Name attribute is State_CountyName. For example, the path for Fulton County, Georgia would have the attribute x:Name=”GA_Fulton”. Periods, commas and apostrophes have been deleted. Multiple word and hyphenated counties have an underscore where the space or hyphen would be. For example, Alaska’s Skagway-Hoonah-Angoon Borough would be x:Name=”AK_Skagway_Hoonah_Angoon”.

Holy cow, Alaska… did you really need to name a county with more letters than the number of people living there?

Anyway, that’s the overview of these files. In the interest of keeping the file size down (no, really! Stop laughing at me!), the county and congressional district boundaries aren’t as details as we might prefer, but that’s the trade-off we have. Also, the county name data is pretty good, but there are over 3100 counties in the US, so I didn’t get a chance to double check each one of the names. Use at your own risk.


How To Create a Flexible Striped Gradient In Silverlight and WPF

7 Comments »

Thanks to Joe McBride and Jason Alderman, who discovered this technique in some of Microsoft’s theme packs.

I’m trying something a little new… I’m going to post all future Silverlight tutorials on CodeRun, an online IDE. Basically, just follow the link below and click “Run” and you’ll see this in action. You can change the XAML at CodeRun to test it out, which I find exceptionally cool. Let me know if you a) like this or b) hate this.

Open this project on CodeRun.

This is just a little trick to get a nice flexible striped gradient in Silverlight or WPF. Our end product will look like this

clip_image001

Zoomed in:

clip_image001[5]

Just adds some nice texture to the app.

First, go to the element you want to apply the gradient to and go to the (you guessed it!) gradient section in the background.

clip_image001[7]

This will pull up the default black-to-white gradient that we all know and love. Give it two more gradient stops as close to the center as you can by clicking on the gradient twice. Make the two left stops the color of your stripe. For this example, I’m using a nice blue gradient with some transparency. I think it fits nice with the background. Also make the two right stops fully transparent. Should look something like this:

clip_image001[11]

Dandy. Now click on the arrow to expand our options (seen at the bottom of the image above) and a new set of options open up for us to futz with. Let’s go ahead and set the following options:

  • StartPoint = 0,0
  • EndPoint = 1.5, 1.5
  • MappingMode = Absolute
  • SpreadMethod = Repeat

clip_image001[13]

And that’s it! We can change the visible color to get something a little more appropriate to our background or we can change the EndPoint to make the stripes wider or at a different angle. But that’s all we need.

Here’s the XAML for reference.

<LinearGradientBrush
EndPoint=”1.5,1.5″
MappingMode=”Absolute”
SpreadMethod=”Repeat”
StartPoint=”0,0″>
<GradientStop Color=”#BF125881″/>
<GradientStop Color=”#BE6C9AE0″ Offset=”0.526″/>
<GradientStop Color=”Transparent” Offset=”0.544″/>
<GradientStop Color=”Transparent” Offset=”1″/>
</LinearGradientBrush>


WPF, Silverlight and Design Links for 09/08/09

No Comments »

I finally cleaned out my Google Reader list and picked out the stuff I like.


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

9 Comments »

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)

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.


Latest SlapDash Version of Wiimote/WPF Visualizer

1 Comment »

I’ve been meaning to totally overhaul my Wiimote WPF visualizer for weeks now and I simply haven’t been able to find the time. But in the meantime, people keep having problems with my old version.

So… my solution is to get my semi-updated version out there. This version works with the latest version of Brian Peek’s Wiimote Library (as of March 10, 2009).

Download Wiimote Visualizer (03_10_09)

Download Wiimote/WPF Binding Library (03_10_09)

Warning: This project WILL break if you try to use the Wii Fit balance board with it. That’s one of the things I’m trying to fix.

Let me know if you have any problems. I will try to address them, but with MIX coming up in a week, it might be a little while. In the meantime, I’m trying to do a complete revamp of all this stuff.


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

3 Comments »

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.


6 Tips For Designers For Translating Your Comps Into XAML

3 Comments »

I’d been holding out on this post in the interest of getting it just right. I think with more time I would add more stuff, but I stumbled across Scott Barnes’ post “I hate it when a designer touches XAML” and I knew that I need to get this posted. Here we have these fantastic tools for integrating the designer more deeply into the workflow and so few people are using it. That’s got to change.

Confession time… I am not, by trade, a designer in the sense that most people use the word… a graphic designer. I try to keep my focus much more on the Usability/UX/Human Computer Interactions/Whatever-The-Cool-Kids-Call-It-These-Days. I do some graphic design if I must, but the fact of the matter is that I’m not really that good at graphic design.

However, I often step in as a go-between for the designer’s comps and the developers code. And one thing that I’m good at is translating comps from Photoshop or Illustrator into XAML for the actual application.

To all designers… I can see why you are disappointed when you see your beautiful designs slaughtered in the translation process… because your designs are beautiful! And with Silverlight and WPF there is absolutely no reason why your designs should not be under your control pretty much all the way through the process. These tips are designed to help ease the transition from comp to user interface.

Pre-Tip: Work in Blend

All of these tips are assuming that designers are building comps with another design tool like Illustrator or Photoshop and then moving the comps into Blend. If you’re not using Blend, you should be. I am not suggesting that you change your design tools or that you design differently. These are just tips for the translation process.

Tip 1: Two layers of semi-transparent gradients is fine. Twelve layers of semi-transparent gradients is not

Whenever you add a transparency layer, you add another run of rendering to all the pixels in that layer. Doing that once or twice is fine… most machines can handle that. But when you have a bunch of them, you’re begging to bring the machine to a crawl. Look at the two gradients below…

gradientcomparison

The one on the right is a solid background with two transparent gradients (a light one at the top and a dark one on the bottom). The one on the left is a single gradient. The one on the right required three passes to render. The one on the left requires one.

This does not mean that you can never have transparency in your application. But if you can figure out an economy of layers when using transparency, you’ll save yourself from from developers who are willing to make the design trade off to speed up the application.

Tip 2: The Grid layout is your new best friend. Understand it. Use it. Love it.

I once worked with a designer who used Blend and made the most beautiful screens with it. But when it came to implement his designs, the developers ended up ditching most of his work because every element was inside a layout inside a layout inside a layout… etc. This ends up being a huge performance killer because every layout means another set of layout calculations for the layout manager.

Instead, make creative use of the Grid layout. Within the Grid layout, you can create columns and rows with the following options:

  • Auto (with Min/Max options) – This column will ask the items inside it how much room they need and will expand or contract to give them exactly the room they need and no more (within the min/max limits).
  • Fixed Width/Height (“80″) – A fixed height or width will take exactly that many pixels of space. Easy enough.
  • Star (“*”) (with Min/Max options ) – this can be used as a decimal or a percentage… “.8*” or “80*”. It asks the container holding it how much room it has. After the Auto and Fixed columns or rows allocate their needed space, the “*” ones take up all the remaining available space unless hindered by the min/max limits.

A single grid can use any number of rows and columns using any combination of Auto, Fixed and Star. You would be shocked at how flexible this is. You can build whole screens using a single grid. I don’t recommend that, but keep the idea of fewer layouts in mind when you are translating designs. Not every element in the project needs to be inside its own layout.

Tip 3: Use Borders, not Rectangles

Borders play nice with pretty much anything you want to do with the added benefit of being able to put stuff in it. Additionally, they are really simple layouts, so they don’t use much overhead. Take a border and put a Grid into it and you have a visually compelling and flexible combination.

Tip 4: Draw simple vector art inside Blend.

Mike Swanson has a fantastic Adobe Illustrator-to-XAML plug-in. I’ve heard that some people can use Expression Design quite well. But unless your project is extremely visual in an artsy kind of way, you should just draw simple vector art inside Blend. Not only will you save yourself the exporting-importing trouble, your XAML will look nicer and be easier to change later on.

I usually draw with the pen tool pentool inside a Grid layout and then use the direct selection tool directselection to make the tweaks I need.

Tip 5: (Silverlight Only) Plan on using only a few fonts

Most of my experience with fonts in Silverlight have been somewhat painful. Hopefully we’ll see that change in Silverlight 3, but in the meantime it is something that I’ve seen even experienced developers fight with. Watch this video by Tim Heuer… it will help. () And put this blog on your RSS feed… I’m working on a step-by-step tutorial for this geared at non-developers.

Tip 6: Work in “Split” mode in Blend and goof around with the XAML every now and again

Blend as a drag-and-drop design tool is absurdly powerful. Using Blend, you could build an interactive wireframe prototype in 15 minutes and never touch a line of code.

But as awesome as it is, it will be necessary from time to time to go into the XAML and tweak this or that or comment something out or copy-paste something else. Simply put, understanding XAML will make transitioning your designs a breeze and having Blend in “Split” mode will let you know just what your work in the design space is doing to the XAML. It’s a pretty painless way to start the XAML learning process.

If you’re interested in getting into the XAML a little more, I would recommend using Visual Studio 2008 in tandem with Blend. It offers intellisense (auto-complete for code) and integrates extremely well with Blend.

Hope that helps… If anyone has any questions, feel free to post them here. If you need more in-depth help, ping me at matthias dot shapiro (at) gmail dot com.


XAML Intellisense for Blend

No Comments »

Karsten Januszewski has a post on getting intellisense into Blend. Apparently it only works for WPF (it “works” for Silverlight, but it pulls from the WPF XML schema, which sounds like it could be more confusing than useful).

I’ve been begging for this for a while. I’m glad to see it in there… its has easily been the biggest missing feature in an otherwise fantastic product.


Follow me: matthiasshapiro