Designer WPF Update

I apologize for my extended sabbatical here… I’ve recently gotten married, which has thrown a bit of a wrench in my blogging commitment.

I’ll start posting again with some regularity in about three weeks, at which point I will also  start working on my first line-of-business Silverlight project. Until then…

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

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

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

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

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

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

Lefty_EditControlParts

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

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

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

 ScrollBar_Visibility

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

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

ListView ScrollViewer will look like this:

ListViewScrollTemplateThe normal ScrollViewer will look like this:

 NormalScrollViewer

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

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

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

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

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

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

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

Change Column to “1″:

Lefty_Column1

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

Change Column to “0″:

Lefty_Column0

  • PART_VerticalScrollBar

Basically, swap everything from in the two columns.

Done.

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

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

</Grid.ColumnDefinitions>

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

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

Go forth and make Ned Flanders proud.

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

WPF Designers Guide to Styles And Templates

This is a post that has taken months to complete, but addresses something that I don’t think I’ve seen sufficiently covered for anyone who is new to WPF. Resultantly, we’re going to go through it slowly and I’m officially begging for additional questions at the end.

Part of the problem with styles and templates in WPF stems from the fact that Blend allows a wonderfully simply way of creating a copy of a template:

SNT_EditControlParts

It then gives you something that looks like this:

<Style x:Key=”My_TemplateTargetType=”{x:Type Button}>
      <Setter Property=”Template>
            <Setter.Value>
                  <ControlTemplate TargetType=”{x:Type Button}>
                        <!– blah blah blah –>

So, from a usability point of view… I told it to create a Template and it created a style. I judged from this that styles and templates were roughly the same thing.

And I was confused.

So, first, I’ll try to explain styles and templates by explaining how they work and then I’ll draw an analogy that I hope is helpful.

Let’s say you have a button.

Hi_Button

You can change all sorts of properties of that button… visibility, background, width, height, margins, border thickness, alignment, font, whatever.

If you have a dozen buttons and you want them all to have the same properties, you can create a button style that specifies those properties and assigns them across the board. You can edit a style in Blend by selecting your control, clicking in the menu: “Objects -> Edit Style -> Edit a Copy…“.

Style editing in the objects tab will look like this.

Style_Objects

As you can see, there are no objects in the visual tree to play with… only properties to assign in the properties tab.

Button_Style_Properties

When you assign a property in Blend, your styles will save that assignment as setters and values. Let’s say we wanted all of our buttons to have green 18 point font  bold text. We could create a style that looked like this:

<Style x:Key=”GreenBorderButtonTargetType=”{x:Type Button}>
      <Setter Property=”ForegroundValue=”#FF00FF00/>
      <Setter Property=”FontSizeValue=”18 />
      <Setter Property=”FontWeightValue=”Bold/>
</Style>

The styles can only define properties that belong to the control type that they are styling (which is defined in the “TargetType“). Also, styles can only give information for properties the control already has and only in the way that the control is already set up. For example, because there is no property for changing the corner radius of a button, you can’t change the corner radius of a button using a button style.

However, what if we want to change something about the button that we can’t change with the given properties? For example, let’s say we wanted to see all the text show up twice.

Double_Button

In order to do this, we need to make what I’m going to call “structural changes” to our control. Structural changes are changes in the actual guts of the control, changes to the base elements that make up the control. For this we need a control template.

Boiled down to their essence, templates are little chunks of XAML that are inserted whenever you use your control. When you right click on something and go to  “Edit Control Parts (Template) -> Edit a Copy…“, Blend takes the default XAML that makes up your control and places it in the resources so that you can change it at your whim.

You can get to the Control Template using the right-click method described at the top of this post. Your basic button template will look something like this:

Button_Template

<Style x:Key=”MyButtonStyleTargetType=”{x:Type Button}>
      <Setter Property=”TemplateValue=”{DynamicResource MyButtonTemplate}/>
</Style>

<ControlTemplate x:Key=”MyButtonTemplateTargetType=”{x:Type Button}>
      <Microsoft_Windows_Themes:ButtonChrome x:Name=”Chrome>
            <ContentPresenter />
      </Microsoft_Windows_Themes:ButtonChrome>
</ControlTemplate>

We can go in and add an additional ContentPresenter in here, like so:

<ControlTemplate x:Key=”MyButtonTemplateTargetType=”{x:Type Button}>
      <Microsoft_Windows_Themes:ButtonChrome x:Name=”Chrome>
            <Grid>
                  <Grid.RowDefinitions>
                        <RowDefinition Height=”.5*/>
                        <RowDefinition Height=”.5*/>
                  <Grid.RowDefinitions>
                  <ContentPresenter Grid.Row=”0/>
                  <ContentPresenter Grid.Row=”1/>
            </Grid>
      </Microsoft_Windows_Themes:ButtonChrome>
</ControlTemplate>

And now our button shows all the content twice, one right on top of another.

The best way I’ve found to think about it is to think of your control as a car.

The dealer give the buyer a list of things that they can change about the car… interior color, leather or fabric seats, 4 or 6 cylinder engine… these are properties of the car… defined in the car “style”. (Basically, you can think of everything that you’re allowed to tweak at this website as the style of the car.)

<Style x:Name=”MySpecialCarTargetType=”{x:Type Camry}>
      <Setter Property=”ExteriorColorValue=”Blue/>
      <Setter Property=”TransmissionTypeValue=”5SpeedManual/>
</Style>

Camery_Basic
 
But let’s say that the buyer doesn’t want a normal seat… she wants a big comfy chair in place of the regular drivers seat. This is something outside of the scope of the list of things she was allowed to choose from, so they have to draw up new blueprints for making this new car. They have to create a new car “template”.

If our normal Camry blueprint looks like this:

<ControlTemplate x:Key=”MySpecialCarBlueprintTargetType=”{x:Type Camry}>
      <CamryFrame x:Name=”CamryFrame>
            <Seat Type=”Drivers/>
            <Seat Type=”FrontPassenger/>
            <Seat Type=”BackBench/>
      </CamryFrame>
</ControlTemplate>

We can go in and replace :

<Seat Type=”Drivers/>

With

<Seat Type=”ComfyChair/>

ComfyChair

You may also notice that, with this model we could get rid of all the other seats except the drivers seat or we could add 12 new rows of seats. We can change anything about the car because we’re down into the original car blueprint.

This is the basic difference between styles and templates.

  • A style is a list of properties that can be assigned in bulk to a control.
  • A template goes a big step further and actually defines the underlying structure of the control.

You may be asking: “So how do these two work together? And what is this Data Template think I keep hearing about?”

Given that this post is getting dangerously long already, I’m going to address those issues in a couple more posts on styles and templates.

I’ll end on this note: if you are working in WPF and you’re having trouble with styles and templates, please read all of these posts (as I get to them) and ask questions in the comments section. I’m pretty good about getting to the comments questions and if the question is big enough, I’ll write a whole post on it. There are few things more vital to a WPF developer/designer than to have a firm grasp on styles and templates. It is in this understanding that the power of WPF really comes out.

  • Who’s The Boss? Property Priority in Styles and Templates (coming soon)
  • Create Conditional Styles and Templates (With the Magic of Triggers) (coming soon)
  • So How Do Data Templates Fit Into All This? (coming soon)

Styling the ComboBox Dropdown (popup)

 This tutorial derives from the general “How to Style the ComboBox” set of tutorials.

First let’s make sure you’re in the right place. In this tutorial, we’re going to style the comboBox drop down (also known as the ComboBox popup) seen highlighted in red below.

CB_Image_1

We will not be styling the items inside the dropdown (highlighted in blue). You can learn how to do that here.

So… let’s just go after some of the basics in styling the dropdown. We’ll give it a new background, a new border and we’ll round the edges to make it just a little more bubbly.

To start out, we’ll need to get to our comboBox control template, so right click on the comboBox in the Objects and Timeline window and go to “Edit Control Parts (Template) -> Edit a Copy…

CB_Image_2

Name it something you like and we’re on our way. 

We’ll be editing the PART_Popup. Whatever you do, don’t change the name to this sucker. Whenever you see a “PART_Something”, it is a necessary part of that specific control (hence the naming convention).

The ComboBox dropdown (which we’ll be calling a popup for the remainder of this post)  is made up of a low cost drop shadow (see more on that here), a border, a scrollviewer and the itemsPresenter.

CB_Image_3

Most of the standard styling we might want to do is probably going to happen in the Border titled DropDownBorder. We can alter the background and the border brushes easily enough by just changing them in the Properties window. But you may notice some quirky behavior from our scrollviewer when we change the CornerRadius. Below, I’ve changed the CornerRadius to “0,0,10,10” and we can see that we lose part of the corner under the scrollviewer.

CB_Image_4

CB_Image_5

We can solve this easily enough by adding some padding through the Border. Below I’ve added a padding of “0,0,2,6“.

CB_Image_6

Better, but not really ideal. In a perfect world, we would be able to say that the border us able to cut off its content in that nice pretty rounded manner.  (If anyone knows how to do that… let me know, I haven’t given it hours of thought yet, but I’d love to know). In this case, however, this sub-optimization is the price we’re going to have to pay if we don’t want to have to go in and mess with the scrollbar style and template.

Usability Design For Forms: Luke Wroblewski

I swear… I’ll get back to the tutorials any day now!

 By in the meantime, I’m doing some form redesign and I wanted to praise to the heavesn Luke Wroblewski, whose many blog posts on form usability is some of the best, most practical stuff I’ve ever seen.

Stuff I’m reading and using right now:

UPDATE: It turns out that Luke was at MIX… a tragedy that I’m discovering this just now. You can see his panel “The Business Value of Design” or read more about it at his website.

MIX 08 WPF/Wiimote Show Off Video

Thought I’d take a moment and toss up the WPF/Wiimote video that we submitted to the MIX 08 Show Off competition:

MIX 08 Sessions Now Online

You can now check out all the MIX sessions, online.

 I attended the following sessions:

Bringing Your Data to Life with Windows Presentation Foundation - Anson Tsao

This is a great crash course to data binding in WPF.

Building Rich Internet Applications using Microsoft Silverlight Part 1 - Mike Harsh and Joe Stegman

Building Rich Internet Application using Microsoft Silverlight Part 2 - Mike Harsh

Good walkthrough  on building a basic Silverlight 2.0 application. You can get the files that accompany this talk at Mike Harsh’s blog. While attending these sessions, Mike and Joe repeatedly reccomended…

Creating Rich Dynamic User Interfaces with Silverlight 2 Controls - Karen Corby

This was possibly the most valuable session I attended. Karen Corby walks us through how to create custom controls in Silverlight. The result is mind-blowingly powerful… and it seemed not to difficult. I hesitate on saying that simply because I haven’t done it myself yet. :-) I’m going to go back over it and walk myself through the whole thing with the source code that she has posted.

Nerd + Art : 10 Code Snippets to Empower Your Inner Artist - Nathan Dunlap and Robby Ingebretsen

Two of the guys from Identity Mine walk through some great code snippets that allow designers a little more freedom to do the work they need to do. You can get the Code Snippet Visual Studio 2008 installer file and some of the samples used in the talk from the Identity Mine website.

Developing Applications with Microsoft VirtualEarth - Chris Pendleton

Christ Pendleton walked us through integrating VirtualEarth into Internet applications. Pretty cool, although I’m not sure how much better than Google’s Maps/Earth API this is. It’s been a while since I’ve played with Google Maps, but I remember it being much easier than I thought it would be. Keep an eye on Chris’ blog, where he’ll be posting the code for the lab shortly (I’m told).

WPF Wii Binding Properties: Infrared Data

This is an extension of my previous post, WPF Wiimote Library (Now With Project Files!), which has links to the WPF Wiimote Binding Library project files as well as some information vital to getting you started in connecting your application to the Wiimote.

And now for the IR properties:

The Wiimote can track up to 4 infrared (IR) LEDs at a time. If I were a programmer, I would have created an IR LED enum with the following properties as part of each IR LED. But since I’m not, these properties can be accessed with the following convention: IR[#][propertyName]. Each IR LED has the following properties:

IR[#]RawPosition

Type: Point

Summary: The IR camera has a X,Y resolution of 1024, 768. This property will give you the raw X,Y position that the Wiimote is tracking this LED at.

Binding Usage Example:

<Grid Canvas.Left=”{Binding Source={StaticResource WiiData}, Path=”IR1RawPosition.X, Mode=OneWay}
Canvas.Top=”{Binding Source={StaticResource WiiData}, Path=”IR1RawPosition.Y, Mode=OneWay}/>

Additional Info: This will work best if your Canvas is the exact dimensions of the Wiimote camera (1024, 768). These properties are automatically converted to take into account the IsMultiPoint setting (described in the Miscellaneous Properties (coming soon)).

IR[#]Position

Type: Point

Summary: This is the X,Y ratio of the position of your IR LED. The best way to use this is in a multi-binding with the width and height of your target Canvas. Fortunately for you, I’ve added a converter that will help with this. Simply add the following code in your resources:

<Wii:VariableCanvasPointConverter x:Key=”VariableCanvasConverter/>

And follow the binding example below.

Binding Usage Example:

<Grid>
   <Canvas.Left>
      <MultiBinding Converter=”{StaticResource VariableCanvasConverter}>
         <Binding Source=”{StaticResource WiiData}Path=”IR1Position.XMode=”OneWay/>
         <Binding ElementName=”MyCanvasPath=”ActualWidthMode=”Default/>
      </MultiBinding>
   </Canvas.Left>
   <Canvas.Top>
      <MultiBinding Converter=”{StaticResource VariableCanvasConverter}>
         <Binding Source=”{StaticResource WiiData}Path=”IR1Position.YMode=”OneWay/>
         <Binding ElementName=”MyCanvasPath=”ActualHeightMode=”Default/>
      </MultiBinding>
   </Canvas.Top>
</Grid>

Additional Info: These properties are automatically converted to take into account the IsMultiPoint setting (described in the Miscellaneous Properties (coming soon)).

IR[#]Found

Type: boolean

Summary: This is a property that is “true” if the Wiimote can see the target LED and “false” if it cannot.

Binding Usage Example:

<Grid IsEnabled=”{Binding Source={StaticResource WiiData}, Path=IR2Found, Mode=OneWay}/>

Additional Info:  This property is also available for the midpoint between the first and second infrared light (MidPointFound) and for the target point (TargetFound) which displays a calculated position of where the Wiimote is being pointed.

IR[#]Size

Type: double

Summary: The Wiimote naturally picks up the size of the LED it is tracking. To get larger sizes  (which translates into better reliability) use a small cluster of LEDs (three should do the trick) rather than a single one.

Binding Usage Example:

<Grid Width=”{Binding Source={StaticResource WiiData}, Path=IR1Size, Mode=OneWay}/>

IsIR[#]Visible

Type: bool

Summary: This item is meant for two way binding. If you want a way to programmatically choose whether or not to show the item that is bound to your IR interface, use this property. It is most useful when used in conjunction with the BoolToVisibility Converter, which can be used by placing this XAML in your resources:

<BooleanToVisibilityConverter x:Key=”boolToVis/>

Binding Usage Example:

<Grid Visibility=”{Binding Source={StaticResource WiiData}, Path=IsIR3Visible, Mode=OneWay, Converter={StaticResource boolToVis}/>

<CheckBox IsChecked=”{Binding Source={StaticResource WiiData}, Path=IsIR3Visible, Mode=TwoWay}/>

Additional Info:  This is a great property to attach to a checkbox (as seen above) to allow user control over which items are to be shown.

In addition to the infrared lights, the WPF Wii library is set up to display two calculated points as well:

  • A midpoint between IR1 and IR2
  • A target point (based on the midpoint) which indicates where the Wiimote is being pointed.

These two calculated points still have the position properties listed above (TargetRawPosition, MidPoint RawPosition, TargetPosition, MidPointPosition) as well as the visibility booleans (IsTargetVisible and IsMidPointVisible) and the “found” boolean properties (MidPointFound and IsTargetPossible).

Of course, you can also play around with the items in Intellisense is also a great way to discover all the available properties.

Show Off Winners!

They’ve just posted the Show Off winners from MIX 08, and my Wiimote Visualization squeaked in at number 3. Here is the complete list of winners:

  1. Crayon Physics Deluxe by Petri Purho
  2. Real Time Physics in Silverlight by Bill Reiss, Andy Beaulieu and Jeff Webber
  3. Wii Data Visualization and Multipoint Nonsense by Matthias Shapiro (that’s me!)

I’ll post the full video on this blog and on the Veracity blog by Monday. Thank you for everyone who attended and voted… and go check out the other videos! There was alot of cool stuff besides physics and Wiimote hacking in those videos. (I’ll post a link when they post one on the MIX site.)

Make Your Own Deep Zoom Images for Silverlight

Have you heard about Deep Zoom?

No… it is not a porno filmed exclusivly with the Canon 5200mm mirror lens (although that would actually be kind of kinky), it is Microsoft’s new, dangerously named technology for taking huge pictures and making them completely zoomable over the internet through Silverlight.

“How huge?” you may ask. Well, I don’t know if there is a hard limit, but the biggest one I saw was 14 petabytes. 

Petabytes. With a “p”. 

Basically, take your bedroom, and fill it top to bottom with those nifty little 500GB external back-up hard drives. And you can see any part of that image almost instantly by simply zooming in on the part you want to see.

To see a demo, you can look at the Hard Rock memorabilia page.

Well, with proper thanks to Robby Ingebretsen, Microsoft has released the Deep Zoom Composer, which allows us normal people to make and implement these kinds of super-zooming interfaces.

I’ll be working on it in the coming weeks and I’ll let you know what I come up with.