Archive for the ‘WPF’ Category
October 1st, 2008
Super cool new thing I learned today. In WPF, we can make it so that the drop down (popup) on a ComboBox displays the data in a ListView. Because of the fact that I believe the DataGrid will eventually overtake the ListView as the gold standard for data display in WPF, we’ll do it both ways.
This tutorial is done entirely in Blend and without a line of code.
Step 0) (for the DataGrid only)
Go to Code Plex and download the WPF Toolkit. Extract to a convenient location.
Right-Click on the References folder in your project tab and click “Add Reference…”

Navigate to the location you extracted the WPFToolkit.dll file, select it and hit OK.
![clip_image001[6] clip_image001[6]](http://www.designersilverlight.com/wp-content/uploads/2008/10/clip-image0016-thumb.png)
Step 1) Select the ComboBox you wish to change and edit the ControlTemplate by right-clicking and selecting “Edit Control Parts (Template) –> Edit a Copy…”
![clip_image001[1] clip_image001[1]](http://www.designersilverlight.com/wp-content/uploads/2008/10/clip-image0011-thumb.png)
Step 2) Find the ItemsPresenter. This is what would normally display our ItemsSource.
![clip_image001[3] clip_image001[3]](http://www.designersilverlight.com/wp-content/uploads/2008/10/clip-image0013-thumb.png)
We’re going to get rid of it. And the ScrollViewer for good measure.
Step 3) Where the ScrollViewer is, put in a ListView or a DataGrid, whichever one you’re using.
![clip_image001[5] clip_image001[5]](http://www.designersilverlight.com/wp-content/uploads/2008/10/clip-image0015-thumb.png)
Now, go the properties of that ListView or DataGrid and click on the box to the right of “ItemsSource”
![clip_image001[11] clip_image001[11]](http://www.designersilverlight.com/wp-content/uploads/2008/10/clip-image00111-thumb.png)
and, in the resulting menu, select “Template Binding –> ItemsSource”.
![clip_image001[7] clip_image001[7]](http://www.designersilverlight.com/wp-content/uploads/2008/10/clip-image0017-thumb.png)
Set the DataContext of the ListView or DataGrid to the DataContext of the parent ComboBox using the same process.
And… you’re done! Open the ComboBox and you will see that you can select items in the ListView or DataGrid in the ComboBox dropdown and see those items change the selection of the ComboBox.
![clip_image001[13] clip_image001[13]](http://www.designersilverlight.com/wp-content/uploads/2008/10/clip-image00113-thumb.png)
You’ll notice that this is probably not yet an ideal solution. For example, when we select an item, the dropdown doesn’t automatically close. Your best bet is to use the SelectionChanged event to trigger some logic to close the ComboBox dropdown.
August 26th, 2008
I’ve recently be working on changing the ControlTemplate of a GridViewColumnHeader in a custom ListView that we’ve been working on. (The ListView was rewritten for sorting, so that’s why it had to be custom.)
One of the things we had to do was swap out ControlTemplates so that we could display a caret to indicate ascending or descending lists. We ended up deciding on ControlTemplates over DataTemplates because the DataTemplates would only work for ListViews that had no custom DataTemplates for the headers. We’re doing all sorts of crazy stuff with our headers and we need to preserve our DataTemplates, so this wasn’t an option.
In any case, I was having no luck finding the resource when I named it this way:
<ControlTemplate x:Key="MyCustomControlTemplate" TargetType="{x:Type GridViewColumnHeader}">
I was using the following code to try and find the resource.
ControlTemplate myNewTemplate = (ControlTemplate)Resources["MyCustomTemplate"];
However, we were able to solve the problem by naming the resource this way
<ControlTemplate x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type local:MyCustomListView}, ResourceId=MyCustomControlTemplate}"
TargetType="{x:Type GridViewColumnHeader}">
And then using this code to access it.
ComponentResourceKey myCustomTemplateKey = new ComponentResourceKey(typeof(SortableListView), "MyCustomControlTemplate");
ControlTemplate myNewTemplate = (ControlTemplate)this.TryFindResource(myCustomTemplateKey);
Just thought I’d pass it along.
August 15th, 2008
This is just a quick note on creating a ListView style with the appropriate GridView style and template assignments.
Normally, I’ve been creating listviews that look like this:
<ListView x:Name=”MyListView”
ItemContainerStyle=”{DynamicResource MyListViewItemContainerStyle}”>
<ListView.View>
<GridView ColumnHeaderContainerStyle=”{DynamicResource MyListViewHeaderStyle}”
ColumnHeaderTemplate=”{DynamicResource MyGridColumnHeaderTemplate}”>
I did this because I didn’t know exactly how to assign these styles and templates to the ListView Style. In the style, ColumnHeaderContainerStyle and ColumnHeaderTemplate are not properties of the ListView, they are properties of the GridView… which you can’t create a style for.
Instead, you can encapsulate all the information above in the following style.
<Style x:Key=”CustomListViewStyle” TargetType=”{x:Type ListView}”>
<Setter Property=”GridView.ColumnHeaderContainerStyle” Value=”{DynamicResource MyListViewHeaderStyle}” />
<Setter Property=”GridView.ColumnHeaderTemplate” Value=”{DynamicResource MyGridColumnHeaderTemplate}” />
<Setter Property=”ItemContainerStyle” Value=”{DynamicResource MyListViewItemContainerStyle}” />
</Style>
Problem solved.
August 7th, 2008
I recently got a comment asking if I could do something on creating a Blend-type ScollViewer styling. The only problem is that the ScrollViewer is a multi-post affair, which I’ll try to get completed in the next month or so. I’m going to go ahead and put up the basics here, much like my Styling the ComboBox and Styling the ListView posts.
In the meantime, I’m making available for download a Resource Dictionary with the Blend ScrollViewer style as I’ve approximated it. (You may have to right-click “Save As…” on that file since IE will do its darndest to open it up.) Just load the resource dictionary into your project and set
<ScrollViewer Template=”{DynamicResource BlendScrollTemplate}” />
Note: This is not the “real” Blend styles… just my rendition/approximation.
In the meantime, here’s the overview for the ScrollViewer. When you look at a template of the ScrollViewer (right-click on the ScrollViewer, got to “Edit Control Parts (Template) -> Edit a Copy…“) you should see something like this:
![clip_image001[7]](http://www.designersilverlight.com/wp-content/uploads/2008/08/clip-image0017-thumb.png)
If you want to change something about the main content area (highlighted below), you’re probably going after the PART_ScrollContentPresenter
![clip_image001[11]](http://www.designersilverlight.com/wp-content/uploads/2008/08/clip-image00111-thumb.png)
If you want to style the corner (highlighted below), look at changing the Corner Rectangle.
![clip_image001[15]](http://www.designersilverlight.com/wp-content/uploads/2008/08/clip-image00115-thumb.png)
If you want to style the HorizontalScrollBar and/or the VerticalScrollBar (highlighted below), you should right-click on either the PART_VerticalScrollBar or the PART_HorizontalScrollBar and go to “Edit Control Parts (Template) -> Edit a Copy…”
![clip_image001[13]](http://www.designersilverlight.com/wp-content/uploads/2008/08/clip-image00113-thumb.png)
A point of note: Because of the way Blend works, it can be difficult to visually style a Vertical and Horizontal ScrollBar in the same Template. Don’t create another template. It’s a waste of time and will make your resources a pain to navigate. I’ll go over exactly what to do in a little bit.
The ScrollBar template should look something like this:
![clip_image001[9]](http://www.designersilverlight.com/wp-content/uploads/2008/08/clip-image0019-thumb.png)
If you want to style the ScrollBar thumbs (the bars you would drag to scroll, highlighted below), you’ll need to change the template for the “Thumb” in the PART_Track. Note: Unless you’re doing something really complex, you should only need to style the Thumb control one time. You don’t need different styles for the vertical and the horizontal.
![clip_image001[17]](http://www.designersilverlight.com/wp-content/uploads/2008/08/clip-image00117-thumb.png)
If you want to style the directional buttons (highlighted below), you will need to change the templates for the first and last “RepeatButton” controls (the ones that aren’t in the PART_Track) using the right-click -> Edit Control Parts (Template) -> Edit Template. (This template should already be copied into your resources.) Again, unless you’re doing something complex, you should only need to style this button one time.
![clip_image001[19]](http://www.designersilverlight.com/wp-content/uploads/2008/08/clip-image00119-thumb.png)
If you want to style the empty area that allows for fast scrolling, you will need to change the style for the two RepeatButtons in the PART_Track (DecreaseRepeatButton and IncreaseRepeatButton)using the right-click -> Edit Control Parts (Template) -> Edit Template. You should only need to do this one time and then apply that style/template across the all the instances of this button.
![clip_image001[21]](http://www.designersilverlight.com/wp-content/uploads/2008/08/clip-image00121-thumb.png)
Over the next couple weeks, I’ll try to put up posts going over how to style all of these into the Blend style. I’ll update this post pointing to the more in-depth tutorials as I go along. Until I get around to doing that, feel free to download the ResourceDictionary with the Blend styles in them.
July 15th, 2008
This is little more than a pointer to a fantastic post by Mike over at Mike’s Code Blog, but I figured it was worth passing along. Mike’s post is focused on finding which item was double clicked, while mine is on determining when the double clicking happened on an item at all.
I’ve recently come up against a problem in which we were attaching a doubleclick event to our listview, only to discover it fires when we did something like click on the scrollbar quickly. Since we only wanted it to fire when we were double clicking on the listview item, we had to come up with some way of figuring out where in the listview the user had clicked.
Mike’s code made it easy… I’m reproducing our permutation of it here:
First, we put our event pointer in the XAML like so:
<ListView MouseDoubleClick=”ListViewDoubleClick”>
Then we put this in the code behind:
protected void ListView_MouseDoubleClick(object sender, RoutedEventArgs e)
{
//grab the original element that was doubleclicked on and search from child to parent until
//you find either a ListViewItem or the top of the tree
DependencyObject originalSource = (DependencyObject)e.OriginalSource;
while ((originalSource != null) && !(originalSource is ListViewItem))
{
originalSource = VisualTreeHelper.GetParent(originalSource);
}
//if it didn’t find a ListViewItem anywhere in the hierarch, it’s because the user
//didn’t click on one. Therefore, if the variable isn’t null, run the code
if (originalSource != null)
{
//code here
}
}
That’s it!
April 18th, 2008
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.
At 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…”

Now we’re looking at the standard listview template. Mine looks like this:
Let’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.

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:
The normal ScrollViewer will look like this:

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″:

- PART_HorizontalScrollBar
- All DockPanels (ListView only)
- PART_ScrollContentPresenter (ScrollViewer only)
- Corner (ScrollViewer only)
Change Column to “0″:

Basically, swap everything from in the two columns.
Done.
If 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=”IsSouthPaw” Value=”True“>
<Setter Property=”Grid.Column” TargetName=”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.
March 27th, 2008
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:

It then gives you something that looks like this:
<Style x:Key=”My_Template” TargetType=”{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.

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.

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

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=”GreenBorderButton” TargetType=”{x:Type Button}“>
<Setter Property=”Foreground” Value=”#FF00FF00” />
<Setter Property=”FontSize” Value=”18“ />
<Setter Property=”FontWeight” Value=”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.

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:

<Style x:Key=”MyButtonStyle” TargetType=”{x:Type Button}“>
<Setter Property=”Template” Value=”{DynamicResource MyButtonTemplate}” />
</Style>
<ControlTemplate x:Key=”MyButtonTemplate” TargetType=”{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=”MyButtonTemplate” TargetType=”{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=”MySpecialCar” TargetType=”{x:Type Camry}” >
<Setter Property=”ExteriorColor” Value=”Blue” />
<Setter Property=”TransmissionType” Value=”5SpeedManual” />
</Style>

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=”MySpecialCarBlueprint” TargetType=”{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” />

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)
March 10th, 2008
Thought I’d take a moment and toss up the WPF/Wiimote video that we submitted to the MIX 08 Show Off competition:
March 10th, 2008
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).
March 7th, 2008
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:
- Crayon Physics Deluxe by Petri Purho
- Real Time Physics in Silverlight by Bill Reiss, Andy Beaulieu and Jeff Webber
- 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.)