Random programming things I'd want to remember

Friday, October 11, 2013

Dealing with "Nested types are not supported" message while working on WPF styles.

I am working on implementing an interface with many buttons on Windows Phone. First thing I learned (the hard way) is that the StackPanel does not support adding controls to it dynamically. Oh well, ItemsControl to the rescue. The tricky part about the ItemsControl is that it lays out its children vertically by default. I did some customizations to help that:

<ItemsControl ItemsSource="{Binding MyProperty}" HorizontalAlignment="Center" Padding="0">  
  <ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
      <StackPanel Orientation="Horizontal" />
    </ItemsPanelTemplate>
  </ItemsControl.ItemsPanel>
</ItemsControl>


All nice and pretty but my interface involves multiple rows of items. Naturally, I can use styles to help me with that! So I open up App.xaml and I start typing:

<Style x:Key="HorizontalStackPanel" TargetType="ItemsControl">
  <Setter Property="Padding" Value="0" />
    <Setter Property="ItemsPanel" Value=...


And this is where I got lost a bit, because the style does not accept nested definitions. Luckily, MSDN has a great example here. This is what I ended up writing:

<Style x:Key="HorizontalStackPanel" TargetType="ItemsControl">
  <Setter Property="ItemsPanel">
    <Setter.Value>
      <ItemsPanelTemplate>
        <StackPanel Orientation="Horizontal"
                    VerticalAlignment="Center"
                    HorizontalAlignment="Center" />
      </ItemsPanelTemplate>
    </Setter.Value>
  </Setter>
</Style>


And everything is working just fine. So this is how anyone can deal with the "Nested types are not supported" message while setting their styles in a somewhat complex way.


No comments: