我創建了一個類田徑代表在播放列表中的歌曲:數據綁定列表框將不會更新
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
設置爲跟蹤狀態,但沒有幫助。我錯過了什麼?謝謝。
謝謝你的回答。我明白爲什麼我的代碼不起作用。但是,我很難實現我自己的'ObservableCollection'類擴展。你能提供一個例子嗎?現在是一門精確的課程(當然會覺得這很棒),但只是爲了理解如何實現'Track'和'NowPlaying'屬性。你可以發佈一個新的答案或者編輯這個答案。再次感謝您的回答。乾杯。 – Boris 2011-03-02 23:37:23
找到它了:http://stackoverflow.com/questions/1427471/c-observablecollection-not-noticing-when-item-in-it-changes-even-with-inotifyp – Boris 2011-03-03 16:16:10