获取Item所选的父ObservableCollection-WP8

本文关键字:ObservableCollection-WP8 Item 获取 | 更新日期: 2023-09-27 18:23:54

我正在编写一个播放流媒体音乐的应用程序,在应用程序中我有很多列表(排名列表、搜索结果列表、突出显示歌曲列表……),每个列表都有一个相同的数据模板,我将其绑定到每个页面的LongListSelector。所以我使用这个数据模板作为资源,并将其放在app.xaml 中

<DataTemplate x:Key="BasicVideoTemplate">
    <Grid Tap="ChangeSong_Tap" RowsAuto="50,50" ColumnsAuto="150,*" Background="White" Margin="5,0,5,10">
        <Grid.ColumnDefinition> 
            <ColumnDefinition Width = "150"/>
            <ColumnDefinition Width = "*"/>
        </Grid.ColumnDefinition>
        <Grid.RowDefinition> 
             <RowDefinition Height = "50"/>
             <RowDefinition Height = "50"/>
        </Grid.RowDefinition>
        <Border BorderThickness="1" BorderBrush="Black" Grid.RowSpan="2" Grid.Column="0" VerticalAlignment="Center" Margin="5,0,5,0">
            <Image Source="{Binding Cover}"/>
        </Border>
        <TextBlock Text="{Binding Name}" Grid.Row="0" Grid.Column="1" Style="{StaticResource BlackTextBlock}" Margin="5,0,0,0"/>
        <TextBlock Text="{Binding Artist}" Grid.Row="1" Grid.Column="1" Foreground="Black" Margin="5,0,0,0"/>
        <!-- .............. -->
    </Grid>
</DataTemplate>

这个代码(我把它放在app.xaml.cs中)从列表中选择一首歌,从这个项目创建一个AudioTrack,然后导航到播放歌曲页面:

private void ChangeSong_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
    var item = (SongItemModel)(sender as FrameworkElement).DataContext;
    App.Model.ChangeSong(item.Id);   /// this code will create a audio track for this item
    (Application.Current.RootVisual as PhoneApplicationFrame).Navigate(new Uri("/Pages/DetailSongPage.xaml", UriKind.Relative));
}

这里的问题是,我必须创建一个列表<AudioTrack>用于我的播放列表,那么我如何获得单击项目的父列表并将其添加到列表<AudioTrack>,而所有这些代码都放在app.xaml.cs??中???

获取Item所选的父ObservableCollection-WP8

我会在每个longlistselectorSelectionChanged事件中处理它。网格上的整个Tap事件让我很不舒服。

<phone:LongListSelector x:Name="myLSS" SelectionChanged="myLSS_SelectionChanged"/>

// event handler changes to
private void myLSS_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    LongListSelector lls = sender as LongListSelector;  // get lls
    var item = (SongItemModel) lls.SelectedItem;
    App.Model.ChangeSong(item.Id);   /// this code will create a audio track for this item

    // now your ObservableCollection is just the ItemsSource, save a reference to it
    // in the State manager so you can reference it on another page if you wish
    ObservableCollection<SongItemModel> obs = (ObservableCollection<SongItemModel>) lls.ItemsSource;
    PhoneApplicationService.Current.State["current_obs"] = obs;
    // navigate..............
    (Application.Current.RootVisual as PhoneApplicationFrame).Navigate(new Uri("/Pages/DetailSongPage.xaml", UriKind.Relative));                 
}