2011-03-01 63 views
0

我創建了一個類田徑代表在播放列表中的歌曲:數據綁定列表框將不會更新

public class Track 
{ 
    public Uri Path 
    { 
     get { return path; } 
     set { path = value; } 
    } 
    public TrackState State 
    { 
     get { return state; } 
     set { state = value; } 
    } 

    private Uri path; 
    private TrackState state; 
} 

接下來,我已經創建MainWindowController類的UI窗口和軌道類之間的交互:

public class MainWindowController : INotifyPropertyChanged 
{ 
    public ObservableCollection<Track> Playlist 
    { 
     get { return playlist; } 
     set 
     { 
      if (value != this.playlist) 
      { 
       playlist = value; 
       NotifyPropertyChanged("Playlist"); 
      } 
     } 
    } 
    public int NowPlayingTrackIndex 
    { 
     set 
     { 
      if (value >= 0) 
      { 
       playlist[nowPlayingTrackIndex].State = TrackState.Played; 
       playlist[value].State = TrackState.NowPlaying; 
       this.nowPlayingTrackIndex = value; 
      } 
     } 
    } 

    private ObservableCollection<Track> playlist; 
    private int nowPlayingTrackIndex; 
} 

基本上,這個類存儲播放列表集合和當前播放軌道的索引。最後,我已經創造了WPF UI窗口:

<Window ...> 
... 
<ListBox 
    Name="PlaylistListBox" 
    ItemsSource="{Binding Source={StaticResource ResourceKey=PlaylistViewSource}}" 
    ItemTemplateSelector="{Binding Source={StaticResource ResourceKey=TrackTemplateSelector}}" 
    MouseDoubleClick="PlaylistListBox_MouseDoubleClick" /> 
... 
</Window> 

背後相應的代碼:

... 
private void PlaylistListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e) 
{ 
    int index = this.PlaylistListBox.SelectedIndex; 
    this.windowController.NowPlayingTrackIndex = index; 
} 
... 

項目源點,其中CollectionViewSource定義靜態資源。 ItemTemplateSelector根據軌道狀態(NowPlaying或Played)定義哪個DataTemplate用於列表框項目。

當用戶雙擊播放列表項目時,MainWindowController中的NowPlayingTrackIndex被更新並更新軌道狀態。問題是,列表框項目的DataTemplates不會在窗口上更新,即雙擊列表框項目不會更改數據模板。爲什麼?

我試着將PropertyChanged設置爲跟蹤狀態,但沒有幫助。我錯過了什麼?謝謝。

回答

0

代碼中有兩個問題需要解決。

首先,你應該知道ObservableCollection通知它的觀察者關於它自己元素的改變,它不知道或關心其元素屬性的改變。換句話說,它不會監視其集合中項目的屬性更改通知。因此,更改PlayList集合中的Track對象屬性值沒有任何意義。這裏是關於這個主題的article

其次,您的MainWindowController根本不會廣播NowPlayingTrackIndex屬性值更改。您應該致電NotifyPropertyChanged("NowPlayingTrackIndex")通知有趣的當事人關於當前播放曲目的變化。這可以解決你的問題,但更優雅的方式,我的建議,將實現一個自定義的ObservableCollection類(如TrackObservableCollection),其中包含NowPlaying屬性,而不是在MainWindowController類中實現它看起來像一個不必要的媒介。

+0

謝謝你的回答。我明白爲什麼我的代碼不起作用。但是,我很難實現我自己的'ObservableCollection'類擴展。你能提供一個例子嗎?現在是一門精確的課程(當然會覺得這很棒),但只是爲了理解如何實現'Track'和'NowPlaying'屬性。你可以發佈一個新的答案或者編輯這個答案。再次感謝您的回答。乾杯。 – Boris 2011-03-02 23:37:23

+0

找到它了:http://stackoverflow.com/questions/1427471/c-observablecollection-not-noticing-when-item-in-it-changes-even-with-inotifyp – Boris 2011-03-03 16:16:10