2013-01-11 37 views
2

我有List<Tuning> tuningslistbox tuningList包含元素:如何刷新列表框在Windows Phone

private void LoadList() { 
      foreach (Tuning tuning in tunings) 
       tuningList.Items.Add(tuning); 
     } 

在應用中的某一點我想刪除tunings一些元素和更新listbox

int selectionIndex = tuningList.SelectedIndex; 
      if (selectionIndex >= 0) { 
       pageTitle.Text = "Deleted tuning"; 
       tunings.RemoveAt(selectionIndex); 
       // tuningList.Items.RemoveAt(selectionIndex); 
       saveData(saver); //saves data to isolated storage 

      } 

但在此之後列表框不會自行更新。編輯:我沒有通過XAML將列表框綁定到集合,我通過LoadList()添加了元素。

<ListBox x:Name="tuningList" Margin="8,0,8,152" Tap="tuningList_Tap"/> 

EDIT2:

<ListBox x:Name="tuningList" Margin="8,0,8,152" ItemsSource=tunings.Items Tap="tuningList_Tap"/> 

EDIT3:

<ListBox x:Name="tuningList" Margin="8,0,8,152" DataContext="{Binding RelativeSource={RelativeSource Self}}" ItemsSource="{Binding tunings}" Tap="tuningList_Tap"/> 

回答

6

我在這種情況下,建議的一塊將您ListBox控制綁定到ObservableCollection<T>,它會自動通知視圖時由於它實現INotifyCollectionChanged,因此項目被添加或刪除。

您需要將集合綁定到ListBox。而不是使用LoadList在XAML中設置ItemsSource。否則什麼都不會發生。

+1

+1打我跳拳:) – Brian

+0

整個應用程序變化太大(沒有足夠的時間)有沒有這麼幹淨的解決方案? – Yoda

+0

你並沒有太多改變,因爲你可以在列表上使用ObservableCollection 上幾乎相同的調用。 –