Monday, January 16, 2012

Surface Tip: Navigating the Visual Tree


There will be times where you will generate dynamic objects on your user interface. A simple example could be loading a collection from a web service and dynamically adding the items to your item controls. Later on you might need to navigate that dynamically generated visual tree to retrieve a specific object or item from it to perform any kind of modifications, which might include even deleting the item, which again will be a common scenario.
Here is how you do it. First you need to pass the DependencyObject that you will be iterating over, which could be for example a ScatterViewItem of a ScatterView control. Then, we will iterate over the children of the DependencyObject using the VisualTreeHelper. Then, what we want to do in this case is to return the associated ContentPresenter object matching the specific content control (the ContentPresenter basically is responsible for displaying the content of a ContentControl). If there is no ContentPresenter on the given children, we perform a bit of recursion to iterate over the child’s children
Ok. Maybe a little bit confusing if we don’t have a purpose. In the previous code sample, what we want is to have a method that we can call to return the ContentPresenter object associated with a specific DependencyObject. A good example will be to retrieve the image ContentPresenter of an Image control that is included on a ScatterViewItem so we can modify the image source. Take the following XAML as an example:
Obviously the previous sample is too basic and it would be a low easier just to give the image a name and reference it from the code behind. But assume that this will be the dynamic XAML generated once you run the application and the user executes an action. Then, you don’t have access to the image item by name reference, so you need to get the ScatterViewItems that in this case was clicked and then use our FindContentPresenter method to get the image content presenter child.
Hope that it makes sense and that can be useful in your Surface 2.0 development.

2 comments:

  1. Take a look at this series of extensions methods for DepeendecyObject which may be useful:

    https://gist.github.com/1623532

    FindVisualChild is a generic version of this method and there are other methods which use similar methodologies to find VisualParent, and Panel instances up and down the visual tree.

    I hope you find them useful.

    ReplyDelete
    Replies
    1. Thanks a lot murven. I wanted to start by a basic approach, but I definitely agree that a more generic version will be more useful. I'll check the references and keep the topic going. Thanks !

      Delete