How can I Create a Bound Animation in WPF?

In a previous post Steve asks "is it possible to bind an animation using xaml?". The example below shows how, binding the duration of an animation to a value in a text box. The animation, which is triggered when the button is clicked, changes the button's background color from orange to brown. The duration of the animation is bound to the value entered in the text box using the same {Binding} markup extension used throughout WPF. »

Author image

How do I Create a Borderless Window in WPF?

I was asked today how to create a borderless window in WPF with no window "chrome" and no gray 3-D border. This is desirable for windows like splash-screens. The Window class in WPF has a property WindowStyle, which can be set to either None, SingleBorderWindow, ThreeDBorderWindow or ToolWindow. While the "None" value sounds exactly like what is required, the window still renders with a gray 3-D border as shown below. To make the window display without this gray border you need to also set the ResizeMode property of the window to NoResize. »

Author image

Hand-Drawn Shapes from Robert Ingebretsen

WPF PM Robert Ingebretsen has released a number of cool WPF resources in the past including the shiny orange buttons and his set of alternate control templates called simple styles. His most recent sample is a serise of hand-drawn shapes - border, rectangle and ellipse. They can be easily used as replacements for their built-in enqivalents, and Robert has supplied full source for those interested in seeing how they work. Here's a simple "boxes and arrows" mind mapping application I was working on converted to use the hand-drawn border. »

Author image

What do I need to install to get started building WPF applications with the June CTP?

The most recent release of WPF is the June CTP - released on the 23rd of June 2006. To begin developing WPF applications for Windows Server 2003 or Windows XP SP2 you need to download the June CTP release of the .NET Framework 3.0 run-time components (WPF is a part of a larger package of new components for windows called .NET 3.0). The .NET 3.0 runtime components are already installed with Windows Vista, but because WPF is more closely integrated into the operating system in Vista than in XP or Windows Server 2003 you need to make sure you have the right version for WPF for your version of Vista. »

Author image

How can I read local files in Browser-Hosted XBAPs?

Xaml Browser Apps (XBAPs - formerly called WBAs) are an a light-weight way of deploying rich WPF applications to users via their web browser. In addition to all the enhanced display features and stateful programming model that WPF apps have over HTML-based internet applications, XBAPs can also touch local system resources like reading from the file system. Allowing applications that run in the browser direct access to the file system would be a huge security risk. »

Author image

How can I display time information more graphically in WPF?

In this code sample I've created a re-usable WPF data template for displaying time information using an analog clock. This demo combines some of the WPF features I've talked about before - DataTemplate and converters, and combines them together for easy display of time information. Here is an example of the DataTemplate in action, used inside the ItemTemplate of a ListBox. It is displaying a list of simple ChatEntry objects - the ChatEntry has one field which is a DateTime.

Chat transcript with times shown using analog clocks

To display the clock showing the time value inside the list's ItemTemplate required the following Xaml. The Content is bound to the DateTime field of the current ChatInfo. It is not apparent in the client code that any special kind of display will be used at all.

Xaml Fragment (WPF Beta 2)
<ContentControl Content="{Binding Path=DateTime}"
    Height="60" Grid.Column="0"
    Grid.Row="0" Grid.RowSpan="2"/>

   
With the abundance of high-quality clock implementations for XAML around it was hard to pick a starting point for the clock DataTemplate. Eventually I chose Nathan Dunlap's attractive chrome-less clock. After stripping it back, removing the animations which made it "go" and the second hand I added it inside a DataTemplate inside my App.Xaml file. This will allow my DataTemplate to be used throughout the application. I wanted my DataTemplate to be used any time a DateTime needs displaying. In order to do this I needed to set the DataType attribute to DateTime for my DataTemplate. The DateTime class that resides in the System namespace in the mscorlib assembly. So that I could specify the DateTime type as the DataType for my template I needed to import the System namespace as shown below:

Xaml Fragment (WPF Beta 2)
<Application x:Class="TimeConverter.App"
    xmlns="
http://schemas.microsoft.com/winfx/2006/xaml/presentation "
    xmlns:x="
http://schemas.microsoft.com/winfx/2006/xaml "
    StartupUri="Window1.xaml"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    xmlns:l="clr-namespace:TimeConverter"
    >
    <Application.Resources>

      <l:TimeToClockHandAngleConverter x:Key="timeToAngleConverter" />
     
      <DataTemplate DataType="{x:Type sys:DateTime}">
      <!-- stripped back clock from Nathan Dunlap in here -->
      </DataTemplate>

       
 </Application.Resources> 
</Application>

As you can see above I also imported the TimeConverter namespace from the current assembly. This is because I needed to write a custom converter for my template, so I could bind the angle of the hands to the number of minutes or hours in the DateTime instance the template was binding against. I wrote a single converter for converting hours and minutes, and passed a parameter to the converter to specify if it should return the angle of the hour hand, or the angle of the minute hand for the supplied time. Inside the DataTemplate the converter was used like this:

Xaml Fragment (WPF Beta 2)
<Rectangle x:Name="HourHand" ... >
  <Rectangle.RenderTransform>
 <RotateTransform Angle="{Binding Converter={StaticResource timeToAngleConverter},
 ConverterParameter=HourHand}"
/>
  </Rectangle.RenderTransform>

Thanks and kudos to Nathan Dunlap for creating a nice and easily subverted clock. You can download a complete sample including the template here.

»

Author image

How can I create a data binding in code using WPF?

When creating UI elements in code it is often necessary to programmatically bind them to data. Fortunately this is relatively straightforward as the following code-snippet using the Binding object from the System.Windows.Data namespace shows:

C# Source (WPF Beta 2)
TextBox nameTextBox = new TextBox();
Binding nameTextBinding = new Binding("Name");
nameTextBinding.Source = person;
nameTextBox.SetBinding(TextBox.TextProperty, nameTextBinding);
// set style on text box, add text box to container etc

This sample assumes you have a type called Person, and an instance called person created elsewhere. Person has a public property called name. First we create our text box (called nameTextBox) and a Binding object, setting the path string for the binding in the constructor. Then we set the data source to the person instance. Alternatively the nameTextBox could get its data through its DataContext or the DataContext of one of its ancestors. If this was the case setting the Source property on the binding would not be necessary.

Next we call the SetBinding() method on the nameTextBox instance, specifying a DependencyProperty and the binding we just created. The example above binds the TextProperty DependencyProperty of nameTextBox to the Name property of the person. In this case the DependencyProperty is a member of the TextBox itself, but it doesn't have to be. For example we can also bind attached properties that might pertain to the container the nameTextBox is placed in.

This example below binds (rather pointlessly) the TopProperty DependencyProperty of the Canvas to the current number of minutes that have elapsed in the current hour for a newly created textbox instance. If the textbox is then added to a canvas (the example assumes a canvas called mainCanvas) the binding will take effect, controlling the top of the textbox in the canvas.

C# Source (WPF Beta 2)
TextBox positionedTextBox = new TextBox();
Binding positionBinding = new Binding("Minute");
positionBinding.Source = System.DateTime.Now;
positionedTextBox.SetBinding(Canvas.TopProperty, positionBinding);
mainCanvas.Children.Add(positionedTextBox);

»

Author image

How do I Include Vector-Based Image Resources in my WPF Application?

WPF is a great platform for creating attractive UI. After working with it for some time you may wish to include vector-based graphics in your WPF application, where in the past you might have used icons or a bitmaps. Using vector-based images in your WPF application allows your images to change size in the same way the rest of your WPF application can, without becoming blurry or blocky.

Recently I came across some nice, crisp-looking free vector images created by N.Design Studio in PDF format. I wanted to see how easy it would be to use them in a WPF application. In this article I'm going to describe the process of converting the images to Xaml, and how Xaml vector images can be packaged up for easy re-use. Thanks to the generosity of Nick at N.Design I'll also post all the Xaml source for the images, which can be freely used in your own open-source and commercial WPF applications.

Converting the Images
To embed images as vectors in a WPF application they need to be in Xaml. Currently there are a number utilities and plug-ins available for converting different file formats to Xaml. Most of these are developed by the community, and are at different stages of completeness and currency. As WPF improves in popularity exporting to Xaml from your favorite tool will become easier and more prevalent. I chose to use Mike Swanson'sAdobe Illustrator > Xaml exporter. After installing the Illustrator CS trial version and following the simple install instructions I was able to open the PDFs in illustrator and export them directly to Xaml. Although this conversion was not perfect, it was more than satisfactory for my purposes.

Adding the Images to a Project
I wanted using the images to be as simple as adding a single file to a project, and knowing the names of the individual images. I added all the images as separate resources with their own keys. Use the technique described in this article to include the external resource file in your main application resources.

Using the Images in WPF
To use one of the image resources use the {StaticResource} markup extension, and the name of the image resource. Here is an example that displays an image resource named "Credit-Card" inside a button.

Xaml Code (WPF Beta 2)
<Button Height="75" Width="220" Padding="2">
  <StackPanel Orientation="Horizontal">
 <ContentControl Template="{StaticResource Credit-Card}" />
 <TextBlock FontSize="16" VerticalAlignment="Center" Text="Pay Now!" Margin="3" />
  </StackPanel>
</Button>

   
The button will look like this:

Button with credit-card image in it, and the text Pay Now

The image resources will resize to fit the available space, and still retain the correct aspect ratio. Here are a number of buttons of different heights with the same image inside them:

Vector images of computer mouse at different sizes

This re-sizing requires no additional code or properties to be set by users of the image, and only minimal effort when creating the resource. To achieve the auto-sizing I nested the "raw" image Xaml (produced by Mike Swanson's converter) inside a Viewbox element with the Stretch attribute set to Uniform:

Xaml Code (WPF Beta 2)
<Viewbox Stretch="Uniform">
 ... <!-- "raw" Xaml - canvases, paths etc go here -->
</Viewbox>

To allow the image resources to be used multiple times the ViewBox (which allowed the images to resize to fit their container) had to be nested inside a ControlTemplate. Objects which derive from FrameworkElement in WPF must normally have a single parent in the tree of WPF objects. Re-using an object deriving from FrameworkElement without first placing it inside a ControlTemplate would result in an error like the following:

Error in markup file 'somefilename.xaml' : Specified element is already the logical child of another element. Disconnect it first.

ControlTemplate allows you to overcome this problem - it has to so that the templates you define for controls like buttons and list boxes etc to be re-used more than once. This technique is described in Chris Sells and Ian Griffiths excellent book Programming Windows Presentation Foundation - p210. After wrapping everything in a ControlTemplate the overall format of all the resources was like the following:

Xaml Code (WPF Beta 2)
<ControlTemplate x:Key="Resource Name">
 <Viewbox Stretch="Uniform">
  ... <!-- "raw" Xaml - canvases, paths etc go here -->
 </Viewbox>
</ControlTemplate>

Here are the images and their names (for easy inclusion in your own WPF projects)

all the converted vector images

Here is the file containing the Xaml code - you are free to use these images created by N.Design Studio in your own projects (both free and commercial) but you are not permitted to re-distribute the Xaml file.

»

Author image

New WPF-related community site from Microsoft

Microsoft has released a new WPF-related community site NextDesignNow targeted at designers working with Microsoft presentation technologies. Although this covers a whole range of things, from sidebar gadgets to designning with InfoCard in mind WPF is given the lion's share of space. Scrolling down through the content shows yet again that brown is the new black when it comes to attractive site design. »

Author image