this has yet to be defined

that is, for you

I’m currently working on a journaling application for WP8. While designing the page for browsing through past entries, I found that I needed to be able to switch between data templates for the LongListSelector housed in the page. Some journal entries would have just text, some would have only a header photo, and some would have both, and I needed to display the entries differently for all three cases.

I found this article describing how to recreate WPF’s DataTemplateSelector class for Windows Phone. It worked fine–after remaking the base abstract class and extending it for my specific case, all you need to do is specify the different data templates in your xaml:

<DataTemplate x:Key="EntryListItemTemplate">
  <sel:EntryItemTemplateSelector>
    <sel:EntryItemTemplateSelector.Both>
      <DataTemplate> <!-- content here --> </DataTemplate>
    </sel:EntryItemTemplateSelector.Both>

    <sel:EntryItemTemplateSelector.OnlyImage>
      <DataTemplate> <!-- content here --> </DataTemplate>
    </sel:EntryItemTemplateSelector.OnlyImage>

    <sel:EntryItemTemplateSelector.OnlyText>
      <DataTemplate> <!-- content here --> </DataTemplate>
    </sel:EntryItemTemplateSelector.OnlyText>
  </sel:EntryItemTemplateSelector>
</DataTemplate>

A bit verbose, but it got the job done thankfully. The LongListSelector would now switch between templates as required.

There was a bit of a problem though.

Mordecai has the right idea.

All of the elements in the LongListSelector were no longer listening to the standard alignment and sizing rules, instead being only as wide as their content and staying put in the center.

I tried adjusting margins, hardcoding widths, HorizontalAlignment=Stretch everything, and either it wouldn’t work, or it would make things even worse.

After a lot of vague googling (what exactly would you call this problem? I honestly had no idea), I arrove at the correct solution. My EntryItemTemplateSelector, inheriting from ContentControl, has a new property named HorizontalContentAlignment, which sets the alignment of the control’s content rather than the control itself. So all you have to do then is

<sel:EntryItemTemplateSelector HorizontalContentAlignment="Stretch">

which gets you

<amp-img width=”768” height=”1280” layout=”responsive” src=”/assets/posts/aligned.png” alt=”“Now every element is taking up the correct amount of space!" title=”“Now every element is taking up the correct amount of space!"></amp-img></figure>

Nothing satisfies Mordecai though.