Archive for the ‘XAML’ Category

Kick it like Beckham with WPF Animations

Thursday, February 21st, 2008

I’m just finishing the Animation-Chapter of my German-speaking WPF book (WPF-Buch erscheint im Juni 2008). I had a hard time to find a good idea how to show the reader animations in a really "non-boring", but easy way. And I think I’ve found one.

Animations in WPF are really powerful. You can create them completely in XAML. Even if the example of this post doesn’t make sense for a business application, think of the things you can do with animations:

  • Create buttons with professional hover-effekts
  • Improve the user-interface with some nice effects
  • Ease navigation for the user by animating something he should do now

Of course, Animations in business applications must be placed in the right way. It’s not recommended to animate everything you can. If you do so, your application won’t be serious anymore.

The application we are looking at here isn’t a business application. It’s just a small Loose XAML-File that allows you to become a soccer profi. :-) It show’s how animations are completely created in XAML and how they can be controlled.

Animations in XAML are placed inside Triggers. Either in an EventTriggers Action-Property or in another Triggers EnterAction or ExitAction-Property. These Properties are all of type TriggerAction. The BeginStoryboard-class and some other classes derive from TriggerAction. BeginStoryboard contains a Storyboard. The Storyboard itself contains the Animations.

Below a loose XAML. The Animation (bold) changes the Canvas.Top-Property of an image that contains a ball (the teamgeist-ball of worldcup 2006 Germany). The Animation starts, when a button with the Name btnStart is clicked. Between the ball-image the Canvas contains an image of me. And the clou is, it looks like I kick the ball for thousand times like a real profi.

<Grid Height="260" Width="300">
 <Grid.RowDefinitions>
  <RowDefinition/>
  <RowDefinition Height="Auto"/>
 </Grid.RowDefinitions>
 <Grid.Triggers>
  <EventTrigger RoutedEvent="Button.Click"
    SourceName="btnStart">
   <BeginStoryboard Name="beginStoryboard">
    <Storyboard TargetProperty="(Canvas.Top)"
      TargetName="imgBall">
     <DoubleAnimation AutoReverse="True" To="110"
     RepeatBehavior="Forever" Duration="0:0:0.25"
     AccelerationRatio="1"/>
    </Storyboard>
   </BeginStoryboard>
  </EventTrigger>
  <EventTrigger RoutedEvent="Button.Click"
    SourceName="btnStop">
   <StopStoryboard BeginStoryboardName="beginStoryboard"/>
  </EventTrigger>
  <EventTrigger RoutedEvent="Button.Click"
    SourceName="btnPause">
   <PauseStoryboard BeginStoryboardName="beginStoryboard"/>
  </EventTrigger>
  <EventTrigger RoutedEvent="Button.Click"
    SourceName="btnResume">
   <ResumeStoryboard BeginStoryboardName="beginStoryboard"/>
  </EventTrigger>
  <EventTrigger RoutedEvent="Button.Click"
    SourceName="btnSpeed2x">
   <SetStoryboardSpeedRatio SpeedRatio="2"
     BeginStoryboardName="beginStoryboard"/>
  </EventTrigger>
  <EventTrigger RoutedEvent="Button.Click"
    SourceName="btnSpeed1x">
   <SetStoryboardSpeedRatio SpeedRatio="1"
     BeginStoryboardName="beginStoryboard"/>
  </EventTrigger>
 </Grid.Triggers>
 <Canvas Width="250" Height="185">
  <Image Height="185" Source="fussballthomi.png"
    Canvas.Left="40"/>
  <Image x:Name="imgBall" Width="25" Canvas.Top="10"
    Canvas.Left="140" Source="teamgeist.png"/>
 </Canvas>
 <DockPanel Grid.Row="1" LastChildFill="False">
  <Button Margin="5" x:Name="btnStart" Content="Start"/>
  <Button Margin="5" x:Name="btnStop" Content="Stop"/>
  <Button Margin="5" x:Name="btnPause" Content="Pause"/>
  <Button Margin="5" x:Name="btnResume" Content="Weiter"/>
  <Button Margin="5" x:Name="btnSpeed1x" Content="1x"/>
  <Button Margin="5" x:Name="btnSpeed2x" Content="2x"/>
 </DockPanel>
</Grid>

Thomas kicks it like beckham. :-)

kickItXAML

More informations about my book, that contains the sample above and hundreds more (also more real world applications), you’ll find by march on www.thomasclaudiushuber.com

Bind to methods with ObjectDataProvider

Thursday, January 10th, 2008

Two classes inherit from DataSourceProvider. XmlDataProvider and ObjectDataProvider. ObjectDataProvider wraps an object and allows you to bind to the wrapped object in XAML. The ObjectDataProvider has a ConstructorParameters-Property for creating an object by using a constructor with parameters.

The cool thing is that a Data Binding to the wrapped object of the ObjectDataProvider is not all. With ObjectDataProvider you can even bind to a static method or to an instance method of the wrapped object. I’ll show you an example.

Just think about a really simple ComboBox that allows the user to chose some colors. Between the name of the color a rectangle filled with the color should be displayed (In WPF this is quite easy. You haven’t to create eventhandlers like you would do in Windows Forms. There you consumed the DrawItem-event of the ComboBox and used the Graphics-object to do a little bit of GDI+. In WPF GDI+ is gone). WPF’s Color class doesn’t have a name property. So just create a static class ColorHelper with one static method GetColorNames that returns an IEnumerable<string> and uses reflection to iterate over all public static properties of the Colors class that all contain Color-objects.

public static class ColorHelper
{
  public static IEnumerable<string> GetColorNames()
  {
    foreach (PropertyInfo p
      in typeof(Colors).GetProperties(
      BindingFlags.Public | BindingFlags.Static))
    {
      yield return p.Name;
    }
  }
}

The Window in the following XAML contains an ObjectDataProvider that uses the Static GetColorNames-Method of the ColorHelper class. The ItemsSource-Property (Typ: IEnumerable) of the ComboBox is bound to the ObjectDataProvider. The ItemTemplate-Property contains a DataTemplate that specifies the Visual Tree (the "look") of an item. Thanks to TypeConverters, a SolidColorBrush-Object is created for the Fill-Property of each Rectangle specified in the DataTemplate.

<Window    xmlns:local="clr-namespace:SimpleObjectDataProvider">
 <Window.Resources>
  <ObjectDataProvider x:Key="colors"
   ObjectType="{x:Type local:ColorHelper}"
   MethodName="GetColorNames"/>
 </Window.Resources>
 <StackPanel>
  <ComboBox
   ItemsSource="{Binding Source={StaticResource colors}}">
   <ComboBox.ItemTemplate>
    <DataTemplate>
     <StackPanel Margin="1" Orientation="Horizontal">
      <Rectangle Fill="{Binding}" Height="10" Width="10"
        Margin="2"/>
      <TextBlock Text="{Binding}" Margin="2 0 0 0"/>
     </StackPanel>
    </DataTemplate>
   </ComboBox.ItemTemplate>
  </ComboBox>
 </StackPanel>
</Window>

The displayed, open ComboBox looks like this:

comboBoxObjectDataProvider

Working with the XmlDataProvider

Monday, January 7th, 2008

The XmlDataProvider class enables Binding to XML inside XAML. This will allow you to bind e.g. to the rss feed of a blog like http://www.thomasclaudiushuber.com/blog/feed/, cause rss is simple XML.

A XmlDataProvider-Element is declared as a logic resource. You simply set the Source-Property to a XML-Document and optionally set the XPath-Property. The default value of the IsAsynchronous-Property of the XmlDataProvider is true, so your client won’t freeze if you specify a url as the source.

The following XAML creates a simple rss-reader. The root is a Window object that contains a XmlDataProvider inside its Resources-Property. The XmlDataProvider loads the feed of this blog and its XPath-Property points to the blogs items. The elements inside the Window are indirectly bound to the XmlDataProvider. They use the DataContext specified on the DockPanel. The special thing of the Bindings on this elements is that they do not directly point to the XmlDataProvider. Instead the Bindings start at the /rss/channel/item like specified in the XPath-Property of the XmlDataProvider. If you want to point directly to the XmlDataProvider-object, you’ve to set the BindsDirectlyToSource-Property of the Binding to true. This is used by the first TextBox. It allows the user to change the Source-Property of the XmlDataProvider to navigate to another feed like http://blog.trivadis.com/blogs/MainFeed.aspx. The Binding for this TextBox also specifies that the UpdateSourceTrigger is PropertyChanged. Without this, the Source would be updated on LostFocus, cause the TextBox.TextProperty has specified this behaviour in its metadata.

<Window x:Class="SimpleRssReader.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/…"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="RSS Reader" Height="600" Width="800">
 <Window.Resources>
  <XmlDataProvider x:Key="blog"
   Source="http://www.thomasclaudiushuber.com/blog/feed/"
   XPath="/rss/channel/item"/>
 </Window.Resources>
 <DockPanel
   DataContext="{Binding Source={StaticResource blog}}">
  <StackPanel DockPanel.Dock="Top"
    TextElement.FontWeight="Bold" Background="LightGray">
   <TextBlock Text="{Binding XPath=./../title}"
     FontSize="20" Margin="10 10 10 0"/>
    <TextBlock Text="{Binding XPath=./../description}"
      FontSize="10" FontWeight="Normal" Margin="10 0"/>
   <TextBox Margin="5" Text="{Binding
     Source={StaticResource blog},
     BindsDirectlyToSource=True,
     Path=Source,
     UpdateSourceTrigger=PropertyChanged}"/>
 </StackPanel>

  <StatusBar DockPanel.Dock="Bottom">
   <StatusBarItem Content="{Binding XPath=title}"/>
   <Separator/>
   <StatusBarItem Content="{Binding XPath=pubDate}"/>
  </StatusBar>

  <Grid>
   <Grid.ColumnDefinitions>
    <ColumnDefinition Width="308"/>
    <ColumnDefinition Width="Auto"/>
    <ColumnDefinition/>
   </Grid.ColumnDefinitions>

   <GroupBox Header="Blog-Eintr?ge">
    <ListBox IsSynchronizedWithCurrentItem="True"
      ItemsSource="{Binding}" DisplayMemberPath="title"/>
   </GroupBox>

   <GridSplitter Grid.Column="1"
     HorizontalAlignment="Center" Width="10"/>

   <Frame Grid.Column="2" Source="{Binding XPath=link}"/>
  </Grid>

 </DockPanel>
</Window>

To test the rss reader yourself, simply create a new WPF-Application Project and paste the XAML above into the Window1.xaml. You have just to set the value of the x:Class-Attribut on the Window-Element so that it matches your class in the Codebehind-File. The Codebehind-File itself doesn’t need any logic. The reader looks like this:

rssreader_XmlDataSource

C# 3.0 and WPF’s ListView

Wednesday, December 12th, 2007

In many applications you want to fill up a ListView or a GridView with some data. In WPF applications you set the View-Property of the ListView to a GridView to show the data nicely in columns. In most cases you have an entity class (think of it as a "real" entity class or a DataRow as part of a DataTable), and objects of this class should be represented in a row of the GridView. In WPF the DisplayMemberBinding-Property of each GridViewColumn is bound to a property of the entity class, so objects of the entity class can be easily added to the ListView and are displayed correctly in the GridViewColumns. But…

The problem (… the problem is more code as you want to have) begins, when you have no entity class and your data is stored in objects of different classes, maybe only in some variables, and you just want to display the data in one row of the ListView. If your variables have a relation to each other, it’s semantically correct to put them into one row of the ListView, displayed in different GridViewColumns. But to display the data in the ListView, you have to create a dummy entity class that contains your data. There’s no other way!

… no other way with C# 2.0. But now we have C# 3.0, and things can get much easier, cause the compiler can create nearly everything for you. :-) To show you how some C# 3.0 features can help you for the problem above with the dummy entity class, I have to step some months back in time and pick out a small sample that exactly shows the necessity of creating a dummy entity class.

Some months ago I created a small WPF application (.NET 3.0 and C# 2.0) to show developers how Routed Events are routed through the Element Tree. The application contains a Button and a ListView. The Button contains a StackPanel and inside this StackPanel is a Rectangle. Below the Window1.xaml:

<Window x:Class="RoutedEventsBeispiel.Window1"
xmlns=="http://schemas.microsoft.com/winfx/2006/xaml/.."
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="RoutedEventsBeispiel" Height="450" Width="500">
 <Grid>
  <Grid.RowDefinitions>
   <RowDefinition Height="Auto"/>
   <RowDefinition/>
  </Grid.RowDefinitions>
  <Button x:Name="button1" Width="100"
          Height="100" Margin="5">
   <StackPanel x:Name="stackPanel1" Background="Black">
    <Rectangle x:Name="rectangle1" Margin="10"
                 Fill="Red" Width="50" Height="50"/>
   </StackPanel>
  </Button>
  <ListView x:Name="listView" Grid.Row="1">
   <ListView.View>
    <GridView>
     <GridViewColumn Header="RoutedEvent"
       DisplayMemberBinding="{Binding RoutedEventName}"/>
     <GridViewColumn Header="Sender"
       DisplayMemberBinding="{Binding Sender}"/>
    </GridView>
   </ListView.View>
  </ListView>
 </Grid>
</Window>

Especially take a look at the DisplayMemberBinding-Property of the two GridViewColumns in the Window1.xaml above. To represent some data in this ListView, the Data must be represented by an object that has a Property RoutedEventName and a Property Sender. Therefore the Dummy class joins the game. Of course the class could be named in a better way like "RoutedEventInfo", but I decided to name it Dummy, because later with C# 3.0 this class won’t be necessary anymore:

public class Dummy
{
  private string _sender;
  private string _routedEventName;

  public string Sender
  {
    get { return _sender; }
    set { _sender = value; }
  }
  public string RoutedEventName
  {
    get { return _routedEventName; }
    set { _routedEventName = value; }
  }
}

In the constructor of Window1 in the codebehind Window1.xaml.cs a general Eventhandler for the Events UIElement.PreviewMouseLeftButtonDown and UIElement.MouseLeftButtonDown is added to the Window, the Button, the StackPanel and the Rectangle. The third parameter of the AddHandler-Method is always set to true. This true stands for "handledEventsToo", so the GeneralOnMouseDown-Eventhandler is called even if any EventHandler has set the Handled-Property of the RoutedEventArgs to true (That’s exactly what the ButtonBase class does internally with the MouseLeftButtonDown-Event, when the ButtonBase class raises its own Click-Event. So the third parameter is necessary here to get the application show the tunneling and bubbling of the events like expected)

public partial class Window1 : System.Windows.Window
{
  public Window1()
  {
   InitializeComponent();

   this.AddHandler(UIElement.PreviewMouseLeftButtonDown…,
    new RoutedEventHandler(GeneralOnMouseDown), true);
   this.AddHandler(UIElement.MouseLeftButtonDownEvent,
    new RoutedEventHandler(GeneralOnMouseDown), true);
   button1.AddHandler(UIElement.PreviewMouseLeftButtonDown…,
    new RoutedEventHandler(GeneralOnMouseDown), true);
   button1.AddHandler(UIElement.MouseLeftButtonDown…,
    new RoutedEventHandler(GeneralOnMouseDown), true);
   stackPanel1.AddHandler(UIElement.PreviewMouseLe…,
    new RoutedEventHandler(GeneralOnMouseDown), true);
   stackPanel1.AddHandler(UIElement.MouseLeftButton…,
    new RoutedEventHandler(GeneralOnMouseDown), true);
   rectangle1.AddHandler(UIElement.PreviewMouseLeft…,
    new RoutedEventHandler(GeneralOnMouseDown), true);
   rectangle1.AddHandler(UIElement.MouseLeftButton…,
    new RoutedEventHandler(GeneralOnMouseDown), true);
  }
void GeneralOnMouseDown(object sender,RoutedEventArgs e)
  {
   if (sender is Window1 
    && e.RoutedEvent==UIElement.PreviewMouseLeftButton…)
   {
     listView.Items.Clear();
   }
   Dummy d = new Dummy();
   d.Sender = sender.GetType().Name;
   d.RoutedEventName = e.RoutedEvent.Name;
   listView.Items.Add(d);
  }
}

The general Eventhandler GeneralOnMouseDown clears the Items of the ListView if the sender is a Window1 instance and the routed event is the tunneling event PreviewMouseLeftButtonDown. After that, it creates an instance of type Dummy, sets its Sender- and RoutedEventName-Property, and adds the Dummy instance to the ListView.

When you click on the red Rectangle located inside of the black StackPanel that is located inside of the Button, the ListView is filled up with Dummy objects, and it shows us, in which order the routed events are raised. The PreviewMouseLeftButtonDown-Events tunnels down from the Window1 to the Rectangle, then the MouseLeftButtonDown-Event bubbles up to the Window1.

20071118_RoutedEvents

That’s the application like I developed it with C# 2.0 and .NET 3.0. The need of the Dummy class is only necessary, because I got two string variables (the name of the routed event and the type name of the sender) that I have to put into one object, and this one object is put into the ListView. The GridViewColumns are bound to the Properties Sender and RoutedEventName of the object inside the ListView, so the Dummy objects are displayed like expected in the correct GridViewColumns.

Now how can I shorten my code with C# 3.0? We just focus on the GeneralOnMouseDown-Eventhandler and the Dummy-class. To add a Dummy object to the ListView, you can just use the Object Initializer to get it done in one instead of four statements:

listView.Items.Add(new Dummy() {
    Sender = sender.GetType().Name,
    RoutedEventName = e.RoutedEvent.Name });

Of course you could alternatively add a constructor to the Dummy-class instead of using an object initializer and you would reach a similar effect. But not always you’re the owner of such a Dummy-class and so you won’t be able to add a constructor. Even if you’re the owner of the Dummy-class, I think you like it to write less code (if you’re not paid per lines of code :-) ). With object initializers you won’t have to create many different constructors.

Now take a look at the Dummy class itself. It could be much shorter, if you use the Automation Properties of C# 3.0 (the IL-Code will still look the similar like before). With automation properties, the compiler creates the backing private fields for the specified properties:

public class Dummy
{
  public string Sender { get; set; }
  public string RoutedEventName{get;set;}
}

We can go even further.

If you’ve read the C# 3.0 specification, you’ve also read about Anonymous Types. So let’s go ahead one more step. Anonymous types are not only a feature that is good to use in LINQ-statements. In this small application here we could throw the Dummy class away and instead of Dummy objects we can add anonymous type objects to the ListView. The anonymous type must contain the properties Sender and RoutedEventName. So without the Dummy class you could fill up the ListView in the GeneralOnMouseDown-Eventhandler just with anonymous types like below, and the application still works the same way:

void GeneralOnMouseDown(object sender,RoutedEventArgs e)
{
  if (sender is Window1 && e.RoutedEvent==…)
    listView.Items.Clear();

  listView.Items.Add(new { Sender = sender.GetType().Name,
    RoutedEventName = e.RoutedEvent.Name });
}

In the background, the compiler creates an Anonymous class, that contains two properties Sender and RoutedEventName. So in IL you’ll find a class created from the anonymous type used above. But that’s not your problem, your C# Code itself gets much shorter.

The cool thing about C# 3.0 and Visual Studio 2008 is that you can use these C# 3.0 features to build .NET 2.0 applications (Of course for WPF applications you need at least version 3.0 of .NET). But be careful when using C# 3.0 features for .NET 2.0 apps. E.g. language enhancement features like LINQ are based on Extension Methods located in assemblies introduced with .NET 3.5. :-)