次の方法で共有


Working with Layout when DataContexts are Involved

Hi everyone,
When using Expression Blend, a common task you probably engage in is working with layout. Tasks I commonly associate with “working with layout” involve moving things around, rearranging the order of elements, ensuring everything flows when resized, changing your layout container, etc. For the most part, the changes you make to the layout of your application are pretty harmless…except when it involves DataContexts.

In a nutshell, data contexts allow you to specify the data that elements can inherit and work with. Seems pretty harmless so far. Data contexts can be set on pretty much anything, but because the data is inherited, data contexts are often placed on parent elements (such as a layout container) whose children will inherit the data:

dataContext

What seemed harmless earlier now has the potential to cause trouble. Because data contexts are often placed on a layout container, and because data contexts primarily benefit any children listening in, you need to ensure that any layout changes you make do not cause your data context to break. The common ways your data context can break are:

  1. Reparenting a Child
    When a child is inheriting data, do not reparent the child to a location where the data context is no longer inheritable. This will cause your child to look for something that doesn’t exist.
     
  2. Ungrouping a Layout Panel
    Blend makes it very easy for you to ungroup children from a layout container. When you ungroup a layout container that has a data context set on it, the data context your children rely on will be lost.

Today, Blend does not let you know when you perform a layout operation that breaks data context. It is up to you to be vigilant, and you can see which element has a data context set on it by looking at its DataContext property:

datacontextproperty

If this property isn’t empty, it means that a data context has been set on it. While having a data context set should not imply that data is actually being used, it is a good gauge on whether a layout operation you perform will have any negative side effects on the children involved.

Cheers!
Kirupa =)

Comments

  • Anonymous
    November 17, 2009
    The comment has been removed

  • Anonymous
    January 28, 2010
    Having worked with Blend for some time now, I've been burned by this a couple of times. Perhaps a warning bubble should appear telling you that a datacontext has been deleted?  This would be the same as when you delete a control that has Visual State on it; you get a warning bubble at the top of the display. I hope a future version (soon!) will include a feature such as this.

  • Anonymous
    July 10, 2010
    Zodman, from what I've seen in the Blend 4 RC, that feature still doesn't exist. As a newbie with XAML, I've already been burned by this. :(