views:

348

answers:

2

Hi,

I have the following list in XAML:

<ListView Name="ListViewBack"
          Margin="3"
          ScrollViewer.HorizontalScrollBarVisibility="Disabled"
          ItemsPanel="{StaticResource IconListPanelTemplate}"
          ItemTemplate="{StaticResource IconListDataTemplate}">
</ListView>

Now I would like to be able to change the ItemsPanel and ItemTemplate from the List to the Grid version. I've tried this using the following code:

ListViewBack.ItemsPanel = Resources["IconGridPanelTemplate"] as ItemsPanelTemplate;
ListViewBack.ItemTemplate = Resources["IconGridDataTemplate"] as DataTemplate;

But nothing happens when excecuted.

Any idea's?

Thanks!

A: 

Your obvious problem is that you are using Resources[] instead of FindResource(). In general, Resources[] will only work if your resource is in the this.Resources dictionary, and not elsewhere.

This is how I would rewrite your two lines of code:

ListViewBack.ItemsPanel = (ItemsPanelTemplate)ListViewBack.FindResource("IconGridPanelTemplate");
ListViewBack.ItemTemplate = (DataTemplate)ListViewBack.FindResource("IconGridDataTemplate");

Acutally I would be more likely to use triggers or use DynamicResource and swap resource dictionaries for this purpose, but that's another story.

Note that I called ListViewBack.FindResource() instead of just FindResource(). This is in case where IconGridPanelTemplate is redefined in a resource dictionary below the UserControl level. If this will never be possible, you can simply call FindResource().

Ray Burns
A: 

You need to style your ListView.View, not the ListView itself. Check the documentation for the ViewBase Class for an example.

majocha