Sunday, October 12, 2008   Search 
Links

 

Disciple
 Ask Dr. WPF Minimize
Author: Dr. WPF Created: 8/13/2007 5:15 PM
Do you have questions about Windows Presentation Foundation that might have broad appeal? Ask Dr. WPF!

My WPF Code Snippets... now available for Visual Basic
By Dr. WPF on 9/22/2008 10:02 AM

I first published my C# WPF code snippets last December in this post.  Due to increasing demand for VB versions of these snippets, I spent this past weekend porting them to VB.  They are now available for both languages. You can download the snippet installer here.

Updated October 1, 2008: 

I just updated the snippets to play nicely with the Strict option in VB.  Grab the latest installer to get a version of the VB snippets that properly casts the result of the CLR get accessors based on the DP type.

All 65 snippets are supported in both C# and VB.NET now.  The shortcuts for the VB versions are slightly different because the VB code editor does not provide the same level of support for snippets as the C# editor  (see rant below). 

In VB, for example, you cannot just type "dp" and hit tab twice to get a list of my dependency property snippets.  Instead, you must type the entire unique shortcut (e.g., "dp2") and then hit tab to expand that specific snippet.  It is probably easier to install all of the snippets within a single category (like "My Code Snippets") and then select the desired snippet from a list, as shown here:

I hope the VB snippets are helpful to a few of you!  Let me know if you find any problems with the ported code.

Cheers,
Dr. WPF

Small Rant Regarding VB Snippet Support

In my earlier post, I talked about how I am looking forward to a day when Visual Studio code snippets will support more advanced macro-like functionality.  After spending some time working with snippets in VB, I realize just how lucky I am to work primarily in C#.  On a scale of Classic Pong to XBox 360, the C# snippet support is probably somewhere around a PS2, whereas the VB.NET snippet support is barely a Nintendo 64!

Come on, Microsoft...  show a little love for that monster base of VB developers you created in the 90's!  At a minimum, at least give them snippet parity with C#.  Here are a few of my complaints:

  • Intellisense should provide snippet hints.
  • The user should not have to tab through every field in the snippet... just the unique fields.
  • There should be support for functions like ClassName().
  • The $end$ tag should be supported.
  • Pressing 'Enter' should take the snippet out of edit mode and place the cursor at the $end$ tag.
  • If there are multiple snippets with the same shortcut, typing the shortcut should provide a filtered list of descriptions for the matching snippets.

Okay, I'm sure most VB developers know how to deal with all these limitations, and since I'm not really part of that constituency, my voice probably doesn't hold much sway in this argument...  so I'm done now.  Enjoy the snippets!

Comments (12)

Ten reasons to check out the new Blendables Layout Mix
By Dr. WPF on 9/19/2008 3:41 AM

Yes, this is a plug for some new WPF goodness from a third party.  If you're simply not interested in third-party products, you can stop reading now.

The good folks at IdentityMine have just released two new "mixes" of WPF controls under their blendables brand (as well as an updated version of their essentials mix).  Both of the new products deal with layout... one targets 2D layout and one targets 3D layout.  I haven't played much with the 3D mix yet, but I have tinkered with the CTP version of the 2D layout mix quite a bit and it contains some definite WPF goodness. For those who are interested in seeing these products in action, a free trial version can be downloaded from blendables.com, including a suite of samples.

Partial Disclosure

Some have insinuated that I might be in the employment of the aforementioned IdentityMine.  It is my policy to neither confirm nor deny any speculation regarding Mine Identity, but to instead encourage all rumors both near fetched and far (and I've heard some good ones!).  Meanwhile, I try to keep my blog focused on WPF goodness, and there is definitely plenty in the newest products from IdentityMine.

In the interest of partial disclosure, I must admit that I know some members of the IdentityMine team, and depending on my mood, I might even call them friends.  They may or may not have encouraged me to review the product.  They certainly did not give me any remuneration for doing so!  (C'mon... shouldn't I at least get a free copy, guys? )

Now for the WPF goodness... 

1. Animation Panels

The layout mix includes more than a dozen panels that can be used for laying out your WPF UI.  These are not just ordinary panels though.  They all derive from a custom AnimationPanel base class.  This base class provides support for animating children of the panel to their appropriate sizes and positions.  As such, if you resize a wrap panel, for example, the children will automatically animate to their new layout positions.  The type and behavior of the animation is easily configured (or even disabled, if desired). 

2. Full Set of Native Panels

The blendables layout mix includes its own implementation of the most common native WPF panels (Canvas, StackPanel, WrapPanel, DockPanel, and Grid).  These panels work exactly like their native counterparts, but since they derive from AnimationPanel, they bring all of the animation goodness to the table.

3. Some Cool New Panels

In addition to the native panels, there are some cool new panels including AnimatedTimelinePanel, AutoStretchStackPanel, CameraPanel, Carousel, RadialPanel, RandomPanel, RelativeCanvas, and StackedStackPanel.  Some of these are self explanatory.  For those that are not, I'd encourage you to look at the samples included with the layout mix to see them in action.  Again, all of these derive from the AnimationPanel base class and provide support for all the animation features in the product.

4. Enter and Exit Animations

One of the questions I receive a lot is, "How do I add enter and exit animations to items in my databound ItemsControl?"  The answer is always that enter animations are easy, but exit animations are rather tricky.  Once an item is removed from the databound collection, its corresponding visuals are automatically removed from the element tree.  This means that there is nothing left to animate out.

The blendables layout mix magically solves this problem by coordinating the lifetime of its children on your behalf.  All you have to do is set the ExitAnimator, ExitAnimationRate, and ExitTo properties (or optionally handle the ChildExiting event and set an exit location in your handler).  There are similar properties for simplifying enter animations.

5. Layout-to-Layout Animations

Another big question since the introduction of the WPF platform is, "How do I implement layout-to-layout animations?"  Again, this is not easily done using the native panels because a child element can only have a single parent.  There is no way to animate a child from one parent to another.  I describe the typical way of simulating layout-to-layout animations in this article.

The Layout Mix offers the first real solution to the layout-to-layout problem by introducing a new panel called SwitchPanel.  This panel exposes a Layouts collection which can contain any number of the other animation panels.  At any given moment, one layout is active.  To switch to another layout, simply change the ActiveLayoutIndex property.  The children of the SwitchPanel will automatically animate to their new positions as determined by the new active layout.  The animation is configurable via the SwitchAnimator and SwitchAnimationRate properties.  This is very cool!

6. Layout-Specific Templates

Each layout specified in the Layouts collection of a SwitchPanel can have its own associated data template.  This is really handy when using the SwitchPanel as the items host for an ItemsControl.  You simply set the SwitchTemplate property on the animation panel.  When that layout becomes active, any SwitchPresenter element within the subtree will be represented using the visuals in the specified SwitchTemplate.

7. Penner Easing Equations

The layout animations, enter and exit animations, and switch animations all leverage a simplified animation model.  You simply set the appropriate "Animator" property using what is referred to in the product as an "iterative animator".  This is simply a frame-based animation class that is used to animate from one value to another value over a given duration or at a specified rate.

The cool thing about the iterative animator approach is that it easily supports Robert Penner's easing equations to drive the animators.  The Penner equations are familiar and appealing to designers that come from the flash world.  Both the layout mix and the 3D mix provide the full set of Penner equations via a static PennerEquations class and the equations can easily be referenced by name in markup.  It looks like this:

<blendables:WrapPanel LayoutAnimator="BounceEaseIn" ... />

8. Extensible Animation Model

You can define your own iterative animators too.  I noticed that the layout mix includes support for all the equations created by Robert Penner, himself.  For example, it contains all 3 of the "bounce" equations:  BounceEaseIn, BounceEaseOut, and BounceEaseOutIn.  However, other developers have gone a step further and defined a BounceEaseInOut version, as shown in this google code project.

I was able to create a similar animator for use in the layout mix by defining my own iterative equation:

public class BounceEaseOutInEquation : IterativeEquation<double>
{
    public override double Evaluate(TimeSpan currentTime, 
        double from, double to, TimeSpan
duration)
    {
        return
( currentTime.TotalSeconds < duration.TotalSeconds / 2 ) 
            ? PennerEquations
.BounceEaseOut.Evaluate(currentTime, from, to, duration)
            : PennerEquations
.BounceEaseIn.Evaluate(currentTime, from, to, duration);
    }
}

Then, I simply needed to define a DoubleAnimator class that used my iterative equation:

public class BounceEaseOutInAnimator : DoubleAnimator
{
    public BounceEaseOutInAnimator()
        :
base(new BounceEaseOutInEquation()) {}
}

To specify my animator for use in an animation panel, I simply define an instance of the animator class as a resource and refer to it using a StaticResource reference, as shown here: 

<Page.Resources>
  <src:BounceEaseInOutAnimator x:Key="BounceEaseInOut" />
</Page.Resources>
  <blendables:SwitchPanel SwitchAnimator="{StaticResource BounceEaseInOut}" ... />

9. Extensible Panel Model

Not only is the animation model extensible, but the panel model itself is also easily extended.  Writing a custom animation panel is very similar to writing any other WPF panel.  In fact, I was able to transform several of my own panels into animation panels very quickly with only a few minor changes.  First, instead of deriving from Panel, I derived from AnimationPanel.  Then, instead of overriding MeasureOverride() and ArrangeOverride(), I overrode MeasureChildrenOverride() and ArrangeChildrenOverride().  Within the latter function, instead of calling the Arrange() method on each child, I called the ArrangeChild() method of the base class and supplied the child as a parameter.  Voîla!  I had a custom animation panel.

10. SimpleBinding and EvalBinding

Some who have seen my responses in the WPF Forum may have noticed that I'm a big fan of a feature called EvalBinding that was part of the blendables essentials mix when it released a couple of years ago.  I'm happy to see that you also get the SimpleBinding and EvalBinding markup extensions as part of the layout mix (and even the 3D mix).

EvalBinding lets you include code expressions in markup as part of a binding.  For the nitty gritty details, you can check out the EvalBinding whitepaper on the blendables site.

Comments (1)

One year ago today...
By Dr. WPF on 8/13/2008 2:32 PM

... Dr. WPF was born!

(Yes, I am a year old now... but I like to think of myself as a very mature 1 year old!)

I can't really think of anything technical to say, but I didn't want this day to go by completely unacknowledged because it's been such a great year, so forgive the rather "social" post.

When I dawned donned (thanks mike! ) my imaginary stethoscope and entered the WPF healing scene (with this post) a year ago, I had no idea what a vibrant community I was entering!  I hope I've at least helped a few folks along in their quest to conquer WPF -- the coolest client platform ever created!

I want to say a sincere thanks to my WPF community cohorts who have made this adventure a ton of fun thus far!

In addition to hanging out virtually with WPF disciples, I get quite a few emails each week with WPF questions.  I certainly try to respond to as many as possible (although the last several months have been super busy, so I apologize to anyone I've missed).  It's encouraging to see how many people are doing cool stuff with WPF.  I originally thought I would be posting more answers publicly, but due to time constraints and the specific nature of the questions lately, I often just find myself responding via email.  But it's all good.

Please keep these questions coming.  If you have general questions, you should definitely post them in the WPF forum first, as you will likely get a response much quicker.  But if you don't get an answer, send me a query and I'm happy to help where I can.  And I know I've been absent from the forum for a while, but hopefully my schedule is going to allow me to hang out there a bit more in the near term.

I'll just leave you with a couple of my favorite posts that people have sent me regarding "Dr. WPF", the character.  (I don't know why, but things like this make me really happy.)

Lots of great info. No offense to the Dr, but the formatting and layout is a bit rough. I prefer to read this one in my RSS reader. (^

No offense taken!  Thanks for the kudos.  The Dr. kinda agrees with you on the formatting.  But hey, with so many great RSS readers out there... 

Dr. WPF's blog entry on that bullshit is exactly why I hate blogs... This guy is worse than a thousand "hay i webprogram blogs" trolls. (^)

Okay... the Dr. doesn't really get it... but it certainly made him smile! 

Any more of these?  Please send me links!  Afterall, if you can't laugh at your imaginary self, who can you laugh at?

And for anyone who really needs something technical to chew on, note that the .NET 3.5 SP1 documentation is now live on MSDN.  Go crazy!

Comments (13)

Airspace Shmairspace
By Dr. WPF on 8/11/2008 8:40 AM

With today's release of .NET 3.5 Service Pack 1, a whole new level of support for DirectX interop is now possible in WPF.  Using the new D3DImage feature in WPF, a custom DirectX scene can now be composed with a WPF scene without the irritating airspace restrictions from medieval days of yore. 

To help developers get started with D3DImage, I have published the following article on Code Project:

     Introduction to D3DImage

This truly is a cool new feature and definitely worth a look! 

Comments (2)

ItemsControl: 'G' is for Generator
By Dr. WPF on 7/20/2008 5:42 AM

In 'I' is for Item Container, we learned that each item within an ItemsControl is represented by visuals hosted within a container element.  The type of this "item container" is specific to the type of the ItemsControl.  For example, the container for an item in a ListBox is the ListBoxItem element.  Similarly, the container for an item in a ComboBox is the ComboBoxItem element.  (A complete list of the native ItemsControl classes and their respective item containers can be found at the end of 'I' is for Item Container.)

In this episode, we examine the mechanism by which item containers come into existence.

Where did these containers come from?

In the previous examples in this series, the item containers have mysteriously (or perhaps magically) been created without our knowledge.  All we typically do is set a binding on the ItemsSource property for the control.  Consider the following ListBox example (again, from 'I' is for Item Container):

<ListBox ItemsSource="{Binding Source={StaticResource Characters}}" 
    ItemContainerStyle="{StaticResource CharacterContainerStyle}">
  <ListBox.ItemsPanel>
    <ItemsPanelTemplate>
      <Canvas />
    </ItemsPanelTemplate>
  </ListBox.ItemsPanel>
</ListBox>

We know that each item in the ListBox is contained within a ListBoxItem.  What we don't know is who created that ListBoxItem.  It is logical to assume that the ItemsControl, itself, created the ListBoxItems, but as we'll see moving forward, this is not the case.

Introduction to the ItemContainerGenerator class

It turns out that every ItemsControl has its own instance of an ItemContainerGenerator object.  This generator is accessible via an appropriately named ItemContainerGenerator property.

As the class name implies, an ItemContainerGenerator provides methods by which item containers can be generated for items within an ItemsControl.  Specifically, an ItemContainerGenerator knows how to create a container and link it to the item it will contain.  It also knows how to remove a container that is no longer needed.  Finally, the ItemContainerGenerator class contains several invaluable methods for mapping existing items within an ItemsControl to their containers and vice versa.

Who really holds the reigns of the generator?

An ItemContainerGenerator knows how to create a container and link it to an item, but who actually gets to decide when this container generation occurs?  You might think that the generator, itself, should get to decide when to do its job, but actually, it intentionally remains "hands off" in these matters.

The ItemContainerGenerator does, however, monitor the collection view of its associated items collection (via a weak event listener for the INotifyCollectionChanged events).  It uses the change notifications to know when to unlink an existing container from an item that is removed, but it never makes a decision on its own to generate a container for an added item.  It just quietly maintains a record of all the items within the collection so that it is poised to create a container at a moment's notice.

If it's not the ItemContainerGenerator, then it must be the ItemsControl, right?  Well, no, the ItemsControl does not directly generate the containers either, but it definitely plays some key roles in the process.  Namely, it creates and owns the "generator" of containers (the ItemContainerGenerator instance) and it gets to decide the type of containers that will be created.

Okay, then who else could possibly be responsible for deciding when containers will be generated?

If you've been following this series for a while, it should be pretty obvious that neither the ItemsControl nor the ItemContainerGenerator can be the sole decision makers in the process because the ItemsControl class supports something called UI virtualization (wherein only visible UI elements are instantiated and added to the element tree).

In 'P' is for Panel, we learned that the items host (a.k.a., the items panel) of an ItemsControl is dynamic.  As such, there is no way for the ItemsControl or its ItemContainerGenerator to generically know when containers will be visible.  Clearly, the items panel must be directly involved in container generation.  After all, the item containers are direct visual children of the items panel.  Since the panel knows precisely where to place these children, it is very logical that it would be the one holding the proverbial reigns of the ItemContainerGenerator and telling it when to generate the containers.

How does the generator know what type of container to generate?

When it is time to generate a container, you might be wondering how the ItemContainerGenerator knows what type of object to instantiate.  Well, really, it doesn't know at all.  Each ItemsControl gets to specify its own type of item container.  The generator simply defers this container creation to its associated ItemsControl by calling its GetContainerForItem() method.  This method is responsible for creating and returning a new container for an item.

What happens if the item is already the same type as the container?

We've previously looked at examples like the following in which a ListBoxItem is added directly to a ListBox:

<ListBox SelectedIndex="0" Width="100">     
  <ListBoxItem>Item 1</ListBoxItem>
  <ListBoxItem>Item 2</ListBoxItem>
  <ListBoxItem>Item 3</ListBoxItem>
  <ListBoxItem>Item 4</ListBoxItem>
  <ListBoxItem>Item 5</ListBoxItem>
</ListBox>

 

 

 

 

You may be wondering what the ItemContainerGenerator does in this case, since the item, itself, is already a container.  Will it create a new ListBoxItem as the container for the specified ListBoxItem?  The answer is no, it will not.  Before the ItemContainerGenerator creates a new container, it first checks to see whether the item, itself, is already a container.  It does this by calling the IsItemItsOwnContainer() method on the associated ItemsControl.

How can we specify our own container type for a custom ItemsControl?

Suppose we wish to create a custom ForceDirectedItemsControl class that will use a physics-aware items panel to host its children.  To enable this scenario, we decide that each container will need to be an instance of a custom ForceDirectedItem class that will support the extra physics-based properties that control item layout in our custom panel (like friction, spring, repulsion, etc).  How can we ensure that our custom ForceDirectedItemsControl class creates the ForceDirectedItem containers?

Well, it turns out that this is pretty easy...  we just need to override two virtual methods in our ItemsControl class:  IsItemItsOwnContainerOverride() and GetContainerForItemOverride()

The following is a typical implementation of a custom ItemsControl class with a custom item container:

  public class ForceDirectedItemsControl : ItemsControl
  {
      protected override bool IsItemItsOwnContainerOverride(object item)
      {
          return (item is ForceDirectedItem);
      }

      protected override DependencyObject GetContainerForItemOverride()
      {
          return new ForceDirectedItem();
      }
  }

Using the above class, when the ItemContainerGenerator is asked to generate a container for an item, it will first check to see if the item is already a ForceDirectedItem.  If not, it will ask the ItemsControl to create a container by deferring to its GetContainerForItemOverride().

Caution:  You should never assume there to be a constant tie between an item and its container.  The GetContainerForItemOverride() method intentionally does not supply the item that will be hosted within the container.  It is the responsibility of the ItemContainerGenerator to link an item to its container.  When a virtualizing panel is hosting containers, it is common to link one item to a container and later link a completely different item to that same container.  This provides a nice perf optimization.

How does UI virtualization work in an ItemsControl?

I previously promised that this episode would include a high level look at exactly how an ItemsControl supports this concept of UI virtualization.  Feel free to skip ahead if you are not curious about the finer details of virtualization.

There are really only two noteworthy panel classes in the framework that take control of the ItemContainerGenerator and instruct it to generate containers:  Panel and VirtualizingStackPanel.

Sidenote:  There is actually a third native class, called ToolBarPanel, that uses the ItemContainerGenerator to generate items for a ToolBar.  We won't really spend any time looking at the ToolBar class in this series, since in many ways it breaks the traditional ItemsControl conventions.  For more, see the note marked "**" at the end of 'I' is for Item Container.

The abstract Panel base class contains what we can consider the default container generation code for panels.  This default logic is simply to generate containers for every item in the collection.  So by default, there is no UI virtualization whatsoever.

The framework contains an abstract class called VirtualizingPanel which derives from Panel and then overrides the default container generation code to replace it with...  well...  nothing.  So if you derive a panel from VirtualizingPanel, it will not generate any containers on its own.  Instead, you will be responsible for implementing the code that leverages the ItemContainerGenerator to generate the containers.

There is only one virtualizing panel included in the early releases of the framework (.NET 3.0 and 3.5).  It is called VirtualizingStackPanel.  And if you paid attention to the chart at the end of 'I' is for Item Container, you know that VirtualizingStackPanel is the default items host for ListBox and ListView.  So we get UI virtualization thrown in for free when we use these controls with their default items panel.

A VirtualizingStackPanel, like any other panel, is responsible for sizing and positioning its children (the item containers).  As such, it knows exactly which children are visible within the viewport of the ItemsControl at any given time.  It uses this knowledge to create, or "realize", only the visible children (plus a few extra on either side of the viewport to enable keyboard navigation to work as expected).  When a realized child is scrolled out of the viewport, the VirtualizingStackPanel queues that container to be removed, or "virtualized", so that its resources can be reclaimed.

If you are writing a custom virtualizing panel, you will also need to implement the logic for realizing visible containers and virtualizing non-visible containers.  Realization consists of generating the container (generator.GenerateNext()) and preparing it to host its item (generator.PrepareItemContainer()).  Virtualization consists of removing the container (generator.Remove()).

We will go deeper into UI virtualization in a future article entitled 'V' is for Virtualization.  In the meantime, if you are anxious to get started writing a virtualizing panel, you should check out Dan Crevier's series on creating a virtualizing panel.

Tying It All Together

We've already covered many different aspects of an ItemsControl in this series and they all come into play in this process of item container generation.  There is a very intricate dance involving an ItemsControl, its items host ('P' is for Panel), its Items collection ('C' is for Collection), and its ItemContainerGenerator ('G' is for Generator... this article).  This dance results in the creation of item containers ('I' is for Item Container) that will host the items directly or host a visual representation of the items, as specified via an item template ('D' is for DataTemplate).

Finding Template Elements by Mapping Items to Containers

A very common question in the WPF Forum is, "How can I get a reference to a specific element in my item template at runtime?"

Sidenote:  In most scenarios, you shouldn't need to do this.  Typically, the reason a person wants to do this is so they can programmatically change a property on some element in the template.  If one carefully develops their view model (which will contain the data items represented within the ItemsControl), this type of property update can be handled via a binding to a property on a data item.

There are certainly a few scenarios where it is necessary to drill into an item's visual subtree to get a specific element.  For these scenarios, we can leverage a couple of nifty methods of the ItemContainerGenerator:  ContainerFromIndex() and ContainerFromItem().  Once you have the container for the desired item, you can locate the element within its visual tree using a recursive routine like the GetDescendantByName() or GetDescendantByType() routines shown here:

  public static Visual GetDescendantByName(Visual element, string name)
  {
      if (element == null) return null;

      if (element is FrameworkElement
          && (element as FrameworkElement).Name == name) return element;

      Visual result = null;

      if (element is FrameworkElement)
          (element as FrameworkElement).ApplyTemplate();

      for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
      {
          Visual visual = VisualTreeHelper.GetChild(element, i) as Visual;
          result = GetDescendantByName(visual, name);
          if (result != null)
              break;
      }
      return result;
  }

  public static Visual GetDescendantByType(Visual element, Type type)
  {
      if (element == null) return null;

      if (element.GetType() == type) return element;

      Visual foundElement = null;
      if (element is FrameworkElement)
          (element as FrameworkElement).ApplyTemplate();

      for (int i = 0;
          i < VisualTreeHelper.GetChildrenCount(element); i++)
      {
          Visual visual = VisualTreeHelper.GetChild(element, i) as Visual;
          foundElement = GetDescendantByType(visual, type);
          if (foundElement != null)
              break;
      }

      return foundElement;
  }

Finding the Container Associated with a Template Element

Similarly, there are times when you will want to handle an event on a specific template element and then locate the ancestor item container for the element.  One option is to walk the ancestors looking for the element by type with the following GetAncestorByType() routine:

  public static DependencyObject GetAncestorByType(
      DependencyObject element, Type type)
  {
      if (element == null) return null;

      if (element.GetType() == type) return element;

      return GetAncestorByType(VisualTreeHelper.GetParent(element), type);
  }

Another perfectly viable approach is to leverage a little fact that we learned in 'I' is for Item Container...  namely, that the DataContext of the container is the very item that it contains.  In most scenarios, this same DataContext will be inherited by all framework elements within the item template.  So you can typically cast the original source of the event to a FrameworkElement and use the DataContext property to get the item that is represented by the template.  You can then use the ContainerFromItem() method of the ItemContainerGenerator to get the container.

Most of these tricks work great for a simple ItemsControl, but then get a little tricky with a HeaderedItemsControl like a TreeView or MenuItem.  For these cases, I strongly recommend leveraging the view model, commanding, and bindings to handle property updates within the view and to respond to user actions within the view model.  We'll explore these things further in future episodes.

Dealing with Asynchronous Container Generation

Alright, clearly the ItemContainerGenerator class provides some very handy, and even essential, methods for mapping items to containers and vice versa.  There is still one very important thing to add to the whole equation... that is the timing of container generation.

Suppose you have a ListBox named CharacterListBox bound to an observable collection named Characters.  You might be tempted to write code like the following:

  private void AddScooby()
  {
      Character scooby = new Character("Scooby Doo");
      Characters.Add(scooby);
      ListBoxItem lbi = CharacterListBox.ItemContainerGenerator
          .ContainerFromItem(scooby) as ListBoxItem;
      lbi.IsSelected = true;
  }

This code will actually result in an exception because the lbi member will be null.  The reason is that containers are generated in a separate dispatcher operation.  As a result, simply setting the ItemsSource property or modifying the bound collection does not cause containers to be created immediately.

The key point here is that we must always think of container generation as an asynchronous operation.  So how can we add an item and then safely locate its container after it has been generated?  For this very purpose, the ItemContainerGenerator class provides a Status property along with change notifications for the status.  If we need to programmatically access containers after they are generated, we can subscribe to the StatusChanged event, as shown in the following code:

  private void AddScooby()
  {
      _scooby = new Character("Scooby Doo");
      Characters.Add(_scooby);
      CharacterListBox.ItemContainerGenerator.StatusChanged
          += OnStatusChanged;
  }

  private void OnStatusChanged(object sender, EventArgs e)
  {
      if (CharacterListBox.ItemContainerGenerator.Status
          == GeneratorStatus.ContainersGenerated)
      {
          CharacterListBox.ItemContainerGenerator.StatusChanged
              -= OnStatusChanged;
          ListBoxItem lbi = CharacterListBox.ItemContainerGenerator
              .ContainerFromItem(_scooby) as ListBoxItem;
          if (lbi != null)
          {
              lbi.IsSelected = true;
          }
      }
  }

There are a couple of important things to notice about this code.  First, the OnStatusChanged() method immediately checks the current status of the generator.  This is important because the status could have changed to one of four different possible values:  NotStarted, GeneratingContainers, ContainersGenerated, or Error.  We should always specifically check for the status that we care about.

Second, as soon as the containers have been generated, the handler removes itself so that it will not be called when subsequent changes to the Items collection cause the generator's status to change.

Bonus Tidbit:  FindAncestor Bindings are Very Handy in Item Templates

This is really just an extra tidbit that I'm tagging onto this topic because of its usefulness.  It is not really specific to container generation. 

Recall that in 'D' is for DataTemplate, we learned how to provide a template of visuals to represent the items in an Items collection.  When dealing with a Selector like ListBox, ListView, TreeView, etc, it is quite common to want to trigger a change in the visuals based on whether an item is selected.  We now know that the concept of selection for these controls is based on the IsSelected property of their respective item containers.  Any element in the item template can be bound to a property of the item container using a FindAncestor binding.

Below is a typical data trigger that might be found in a DataTemplate for an item within a ListBox:

<DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor,
    AncestorType={x:Type ListBoxItem}}, Path=IsSelected}" Value="True">
  <Setter Property="Foreground" Value="#A1927E" TargetName="tb" />
</DataTrigger>

Up Next

In the next episode of this series, I plan to examine the "lookless" nature of ItemsControls.  Please stay tuned!

Comments (12)

Leveraging Freezables to Provide an Inheritance Context for Bindings
By Dr. WPF on 5/22/2008 8:04 PM

Mike Hillberg has some great observations about WPF application architecture as it pertains to model interaction in his "Model See Model Do" post.  I am very much in agreement with Mike on this subject.

And let me also say that I'm very happy to see Mike posting a bit more on WPF recently. 

There is another thing definitely worth highlighting in Mike's latest post... In his code sample, he uses a little trick to ensure that bindings on his command and argument objects resolve correctly.  Namely, he derives them from Freezable:

    public class MethodCommand
        : Freezable // Enable ElementName and DataContext bindings

    public class MethodArgument
        : Freezable // Enable ElementName and DataContext bindings

Normally, ElementName and DataContext bindings are resolved based on the target dependency object's position within the element tree (or the namescope to which the target dependency object belongs).  But in this case, the target dependency object is not actually in the tree.  Instead, it is just a property value on another object.  That other object may or may not be in the tree.

The reason the Freezable trick works is because a Freezable object has its own notion of "inheritance context".  When the property engine sets the effective value of a dependency property, it looks at that new value to determine whether it is a dependency object that would like to be part of a special inheritance tree.  A Freezable is one such object that always wants to be in the inheritance tree when not frozen.  As such, when the Command property on Button is set to a Freezable in Mike's example (below), the framework adds the Button itself as the inheritance context of the Freezable.

    <Button Content="Rename"> 
      <Button.Command>
        <mc:MethodCommand MethodName="Rename">
          <mc:MethodArgument Value="{Binding Text, ElementName=_
renameTextBox}" />
        </mc:MethodCommand
      </Button.Command>
    </Button>

The MethodCommand object above will now have the Button as its inheritance context. As such, even though MethodCommand is not a FrameworkElement with a tree-inherited DataContext property, it still effectively inherits the data context of the Button.  A binding on any property of the MethodCommand object will use its inheritance context to arrive at an implicit binding source (which will be the DataContext of the Button in this case).

The same construct is used to pass the inheritance context from a MethodCommand to its MethodArgument objects, so that their bound properties, too, can be resolved.

(Note that a Freezable can also have more than one inheritance context, but I'll leave the discussion of how multiple inheritance contexts are handled for a future post.)

In addition to the above scenario (where a freezable is set as a dependency property value on a dependency object), it is this enhanced notion of an inheritance tree and inheritance context that allows bindings on brushes, animations, and other freezable objects to work when those objects are placed within a resource dictionary.

Mike's approach is definitely a cool trick and I've used it myself on occasion.  Of course, there are scenarios where inheriting from Freezable is not really an option.  In such situations, the hack I find most useful for enabling bindings on non-freezable objects is to artificially add such objects to the logical tree.  But I would love to see Microsoft publicly expose the ability to control an object's inheritance context so that all these hacks could just go away.  (Hint, hint! )

 

Comments (5)

I've been Pixel8ed!
By Dr. WPF on 5/15/2008 4:00 AM

If you are tired of reading my occasional ramblings, you now have the option of "listening" to me expound on the merits of WPF! 

Craig Shoemaker has just published this podcast on the Infragistics Pixel8 site.  I probably reveal a bit too much about myself in this interview, so if you want to preserve the mystery and romance of our relationship, maybe you shouldn't listen to it!   

(What do you mean, you're not feeling the romance anymore?)

Comments (1)

The Emancipation of Visual Children
By Dr. WPF on 4/7/2008 2:37 AM

hen in the course of elemental events it becomes necessary for one collection [of children] to dissolve the visual bands which have connected them with another and to assume among the powers of the framework, the separate and equal station to which the Laws of WPF and of WPF's Disciples entitle them, a decent respect to the opinions of element-kind requires that they should declare the causes which impel them to the separation.

We hold these truths to be self-evident, that all elements are created equal, that they are endowed by their Parser with certain inalienable Rights, that among these are... well, pretty much just Liberty.

And the same thing goes for Logical children!


Okay, it's very possible that I'm enjoying the HBO miniseries on John Adams just a little too much. 

Why am I declaring independence for visual and logical children?

Because of the coolness that it enables in WPF!   If you'd like to know more about my epic struggle to free the visuals, please check out the article that I published this past weekend on The Code Project:

     Conceptual Children:  A powerful new concept in WPF

A few people have suggested that I should write a book called "Hacking WPF."   (Okay, certainly no publishers have suggested such a thing... just some of the folks I work with.)  I'm sure someone is already working on the book and I don't think I could ever reconcile the book title with my view of what I do for a living.  I like to think of myself as a moderately sophisticated developer (rather than a hacker) that embraces and leverages the strengths of the platform.  BUT...  If I ever were to write such a book, this would definitely be the type of article it would include!

Warning:  It's pretty geeky and perhaps on the advanced side of intermediate.

Comments (3)

ItemsControl: 'R' is for Rob has a Customer
By Dr. WPF on 3/28/2008 1:15 AM

Rob Relyea has a customer (I wonder if it's Kevin's Mom?) who is looking for an implementation of this Views menu that is used in Vista's Explorer window. 

Since I haven't seen anyone respond, I put together a little app to demonstrate how you might do this in WPF.  (Yes, I'll use any excuse to knock off another letter of the alphabet in this series!)

This really does qualify for the ItemsControl series.  Not only is a ContextMenu an ItemsControl, but I also demonstrate how to use the menu to control another ItemsControl... a ListView.  In total, this sample demonstrates binding to a collection ('C' is for Collection), creating a dynamic item template ('D' is for DataTemplate), and using triggers to adjust properties on a custom items panel ('P' is for Panel).

One would typically implement a user control for a menu like this because the control is really a collection of several other controls (in this case, a slider, several menu items, and a popup) with well-defined, static visuals .  However, because I wanted several behaviors that come for free with a context menu, I just took a shortcut and derived directly from ContextMenu.  I used the control's template to define the visuals.  Make no mistake... this is not a "custom control" in the WPF lookless sense of the term.  The implementation is very much tied to the visual elements in the template.

Disclaimer:  This is just an example of how such a menu could be constructed.  I readily admit that I didn't spend much time on it and there are lots of improvements that could be made.  Also, there are some interesting behaviors within the Views menu in Vista.  For example, the menu is always opened such that the slider's thumb is directly under the mouse.  I implemented this feature and some of the others that I noticed, but I didn't spend a lot of time trying to precisely imitate all the behaviors.  There's certainly still some cleaning up to be done if you require pixel perfection in sizing, iconography, etc.

Download the complete sample here. 

Comments (15)

ItemsControl: 'I' is for Item Container
By Dr. WPF on 3/25/2008 7:10 PM

Oh look... I did it again!  I promised to write 'G' is for Generator and then I come out with 'I' is for Item Container.  I'm like a bad TV series that just keeps leading you on... Then just when you think you're about to discover the true identity of the evil mastermind, the plot takes an unexpected turn.  Please tune in next time when we'll unveil... The Generator!

Okay, this episode isn't really a departure from the plan.  I simply realized that I had too much content for a single post, so I broke our look at item containers and item container generation into two separate issues.  If it makes you feel better, you can think of this as 'G' is for Generator, Part I.  Although we won't actually talk about container “generation” in this episode, we will lay the groundwork by talking about the containers that get “generated”.

In our last episode, 'P' is for Panel, we discovered that an ItemsControl leverages a panel to layout its children.  We call this panel the items host (or the items panel).  It seems quite appropriate to use a panel to layout the items, since that is exactly the purpose for which a panel is designed... namely, to size and position a collection of visual children.

In an earlier article, 'D' is for DataTemplate, we saw that a data template can be used to specify the visuals that represent an item within the Items collection of an ItemsControl.  And since any object can belong to the Items collection, this architecture allows for a diverse and disparate collection of visuals within an ItemsControl. 

A Motley Crew of Items

Consider the following example:

  <ItemsControl HorizontalAlignment="Left">
    <TextBox Name="tb" Margin="2" Text="Test" />
    <sys:String>http://drwpf.com/blog/</sys:String>
    <sys:String>http://forums.microsoft.com/MSDN/</sys:String>
    <x:Static Member="ApplicationCommands.Copy" />
    <x:Static Member="ApplicationCommands.Cut" />
    <x:Static Member="ApplicationCommands.Paste" />
    <x:Static Member="ApplicationCommands.SelectAll" />
  </ItemsControl>

This ItemsControl has 7 items explicitly added to its Items collection:  one TextBox, two strings, and four routed commands.  You could easily define a data template for the String type to display the strings as hyperlinks and another data template for the RoutedUICommand type to display the commands as buttons.  Then the ItemsControl might have the visual representation shown here.

Since a StackPanel is the default items host for an ItemsControl, the children are nicely stacked.  If you'd like to observe this example in Kaxaml (or XamlPad if you're old school), the very simple markup is available here.

Some Common Problems to Consider

Below are several common problems that need to be considered when working with an ItemsControl in WPF.  We should keep these in mind as we look at item containers in this post and item container generators in the next episode.

Problem 1:  Custom Child Placement

A panel is capable of arranging all types of UI elements, so it can certainly handle such a motley crew of children, but imagine that the panel is a Canvas and you want to provide custom placement of the items within your collection.  In this case, you would need to set the attached Canvas properties (Canvas.Left, Canvas.Top, etc) on all of the differing elements in your collection of children.  This could be a real hassle to maintain with so many different types of visuals.

Problem 2:  Mappings between Items and Visuals

And remember that the actual items may simply be string or command objects.  These objects have no inherent visual representation without their data templates.  Once a data template has been inflated for an item and the visuals have been added to your ItemsControl, how do you map the visuals back to the items and vice versa?

Problem 3:  UI Virtualization

What if there are thousands of items in your ItemsControl?  Unless the items are very small, they will not all appear within the viewport of the control at the same time.  We definitely do not want to pay a high performance penalty for instantiating visuals for items that are not visible.  How can we make sure that only visuals for the visible items (give or take a few) are in memory at any given moment?

Problem 4:  Consistent Item Chrome

Another thing that you might want to do in an ItemsControl is provide a common “chrome” for each item.  Since the items themselves can be quite diverse and the items panel might not be something as predictable as a StackPanel, an ItemsControl might sometimes appear haphazard.  One way to bring a sense of uniformity to such a collection is to provide a consistent background or chrome for each item.  Is it possible to do this without directly adding the chrome to the item's data template?
 
Problem 5:  Visible Selection State

Finally, if the ItemsControl is a Selector (e.g., ListBox, ListView, TreeView, ComboBox, etc), how would you go about showing a uniform selection state for all of the differing children?

It would certainly be a lot easier to deal with all of the above issues if the children of the items panel were all the same type of element.  Enter the item container...

What is an item container?

An item container is an automatically generated "wrapper" element for items within an ItemsControl. It is called an item container because it actually “contains” an item from the Items collection.  More specifically, the container is the control which contains the visual representation for an item.  If the item has a data template, the container is the control into which that data template is inflated.

Let's revisit a simple ListBox example that we saw earlier in 'D' is for DataTemplate.  Here is a ListBox that displays a collection of Characters:

  <ListBox ItemsSource="{Binding Source={StaticResource Characters}}" />

Note that we're using a ListBox in ItemsSource Mode (see 'C' is for Collection).  The collection of characters is the same as before:

  <src:CharacterCollection x:Key="Characters">
    <src:Character First="Bart" Last="Simpson" Age="10"
        Gender="Male" Image="images/bart.png" />
    <src:Character First="Homer" Last="Simpson" Age="38"
        Gender="Male" Image="images/homer.png" />
    <src:Character First="Lisa" Last="Bouvier" Age="8"
        Gender="Female" Image="images/lisa.png" />
    <src:Character First="Maggie" Last="Simpson" Age="0"
        Gender="Female" Image="images/maggie.png" />
    <src:Character First="Marge" Last="Bouvier" Age="38"
        Gender="Female" Image="images/marge.png" />
  </src:CharacterCollection>

We can define a very simple data template to display the characters:

  <DataTemplate DataType=" {x:Type src:Character} ">
    <StackPanel Orientation="Vertical" Margin="5">
      <TextBlock FontWeight="Bold" Text="{Binding First}"
          TextAlignment="Center" />
      <Image Margin="0,5,0,0" Source="{Binding Image}" />
    </StackPanel>
  </DataTemplate>

This gives us the ListBox at the right.

Where's the container?

Supposedly, the visuals for each of the characters in this example are wrapped within an item container.  But I don't see a container!  Where is the container?  More importantly, what is the container?  The answer to that question actually depends on the ItemsControl.  In this case, the ItemsControl is a ListBox.  The item container for a ListBox happens to be a control called ListBoxItem.

You may not think you see a ListBoxItem in the control, but if you select an item, you will notice that the background of the entire selected item becomes blue and the TextBlock within the selected item shows up with a white Foreground (see the image below).  The blue that you are seeing here is the background of the item container.

These visual changes happen automatically without any changes to our Character data template.  They are the result of the template within the default style for ListBoxItem, (along with some triggers in that template).
 
Wow!  The container has a pretty important role in this scenario, especially if you think you might like to alter the visuals used to depict item selection.  Clearly, this merits further investigation...

Understanding the Item Container and its Style

As just mentioned, the selection state for a ListBoxItem is defined within the control's style and template.  Anytime you are working with an ItemsControl, I strongly recommend that you take time to understand the control's item container as well as the default style for that container.  So let's just take a moment to look at some aspects of ListBoxItem and the default ListBoxItem style, as defined for the Vista Aero theme (from Aero.NormalColor.xaml).

  1. The Background of the ListBoxItem is set to Transparent.  This is important.  By using a Transparent brush rather than the default null brush, the ListBoxItem becomes hittable (or visible to hittesting by input devices).  In other words, a mouse hittest will find the item, thereby allowing it to be selected when the transparent portion is clicked. 
     
  2. HorizontalContentAlignment and VerticalContentAlignment on the ListBoxItem are data bound to the properties of the same names on ListBox.  As such, if you'd like all ListBoxItems to left-align their content, you can simply set HorizontalContentAlignment to Left on the ListBox itself.  This is very handy to know and you probably wouldn't know it without looking at the style.  
     
  3. The default template for ListBoxItem consists of nothing more than a ContentPresenter within a Border. 
     
  4. ListBoxItem exposes a dependency property called IsSelected.  This is pretty common for the item container of a Selector control.  In fact, the Selector class is where the IsSelected property is originally registered with the property engine.  ListBoxItem and other containers simply add themselves as owners for the property.  As such, Selector.IsSelected provides a useful trigger property for showing that a container is selected.  
     
  5. There are indeed several triggers within the control template that alter the container's appearance based on whether it is selected, active, and/or enabled.

Sidenote:  If you are new to styling and templating in WPF, recognize that all of the native control styles and templates are available in theme files that ship as part of the framework SDK or with Blend.  There are actually many different ways you can view these styles, as I describe in this forum post.  Designers often go straight to a tool like Blend, when they want to explore/modify a control template.  This is certainly fine too, but I prefer going to the theme file so I can see both the style and template declarations together.

The ItemContainerStyle Property

That's great!  Now we understand the default style and template.  What can we do with this knowledge?  Well, quite a bit, actually.  It turns out that it's very easy to define our own item container style.  We simply need to set the ItemContainerStyle property of the ItemsControl, as shown here:

  <ListBox ItemsSource="{Binding Source={StaticResource Characters}}"
      ItemContainerStyle="{StaticResource CharacterContainerStyle}" />

Next, we need to define the style.  We will use the container style to add some standard chrome to the items in our ListBox by redefining the ListBoxItem's template, as shown below.  You don't need to get too wrapped up in the nitty gritty of this style (unless that's your thing).  Just note that there are a handful of properties being set, and one of them happens to be the Template property.

  <Style x:Key="CharacterContainerStyle" TargetType="{x:Type ListBoxItem}">
    <Setter Property="Background" Value="#FF3B0031" />
    <Setter Property="FocusVisualStyle" Value="{x:Null}" />
    <Setter Property="Width" Value="75" />
    <Setter Property="Margin" Value="5,2" />
    <Setter Property="Padding" Value="3" />
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="{x:Type ListBoxItem}">
          <Grid>
            <Rectangle StrokeThickness="1" Stroke="Transparent"
                RadiusX="5" RadiusY="5" Fill="White"  />
            <Grid>
              <Rectangle x:Name="BackgroundRect" Opacity="0.5" StrokeThickness="1" 
                  Stroke="Transparent" RadiusX="5" RadiusY="5" 
                  Fill=" {TemplateBinding Background} " />
        &nbs