Jon Jon - 25 days ago 29
C# Question

uwp switch data template - rebinding itemsource

I'm making a win 10 universal app and I have two arrays of objects:

private ObservableCollection<Song> Songs;
private ObservableCollection<JonPlaylist> Playlists;


and a listview to display the data inside of them:

<Page.Resources>
<DataTemplate x:DataType="data:Song" x:Key="SongDataTemplate">
<StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Name="ListSongName" Text="{x:Bind Title}" VerticalAlignment="Bottom" HorizontalAlignment="Left"/>
<TextBlock Name="ListArtist" Text="{x:Bind Artist}" VerticalAlignment="Bottom" HorizontalAlignment="Left"/>
</StackPanel>
</StackPanel>
</DataTemplate>

<DataTemplate x:DataType="data:JonPlaylist" x:Key="PlaylistDataTemplate">
<StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Name="ListSongName" Text="{x:Bind Title}" VerticalAlignment="Bottom" HorizontalAlignment="Left"/>
</StackPanel>
</StackPanel>
</DataTemplate>

</Page.Resources>


Listview:

<ListView Name="SongListView" ItemsSource="{x:Bind Songs}" IsItemClickEnabled="True"
ItemClick="SongListView_ItemClick"
ItemTemplate="{StaticResource SongDataTemplate}" />


The problem is that I want to be able to switch between the two arrays/collections which are of different data types.

I've been trying to accomplish this with the data templates as page resourses, and rebinding the listView.ItemSource and listView.ItemTemplate:

private void SwitchViewButton_Click(object sender, RoutedEventArgs e)
{
SongListView.ItemsSource = Playlists[0].GetType();
SongListView.ItemTemplate = this.Resources.ElementAt(1);


}


However I do not know if this will work. Will it be better to utilize user controls and a visual state manager?

Answer

Rather than trying to rebind/re-template a single list view, why not have two list view controls and show/hide them as required?

I would very much recommend using the VisualStateManager to do this and employing the x:DeferLoadStrategy="Lazy" to address performance concerns.

Let me know if you need further information about any on the above.

Comments