Jon Jon - 1 year ago 174
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:

<DataTemplate x:DataType="data:Song" x:Key="SongDataTemplate">
<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"/>

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



<ListView Name="SongListView" ItemsSource="{x:Bind Songs}" IsItemClickEnabled="True"
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download