2011-12-08 24 views
0

我是ObservableCollections的新手,但已經構建了一些我確信應該可以工作的代碼。不幸的是,它沒有。唯一沒有發生的事情是,我的GUI沒有被更新。我知道後面的值正在更新(使用調試器進行檢查)。Silverlight UI不更新 - ObservableCollection被重新使用

我在做什麼錯?

與我的XAML的文字塊的樣本

這裏:我的代碼

<TextBlock Name="tbCallsOpen" Text="{Binding IndicatorValue}" /> 

。由此樣本背後:

public partial class CurrentCalls : UserControl 
{ 
    Microsoft.SharePoint.Client.ListItemCollection spListItems; 
    ObservableCollection<CurrentCallIndicator> CallIndicators = new ObservableCollection<CurrentCallIndicator>();   

    public CurrentCalls() 
    {    
     InitializeComponent(); 

     DispatcherTimer dispatchTimer = new DispatcherTimer(); 
     dispatchTimer.Interval = new TimeSpan(0, 0, 20); 
     dispatchTimer.Tick += new EventHandler(BindData); 
     dispatchTimer.Start(); 
    } 

    private void BindData(object sender, EventArgs args) 
    { 
     //splistitems is a sharepoint list. Data is being retrieved succesfully, no issues here. 
     foreach (var item in spListItems) 
     { 
      //My custom class which implements INotifyPropertyChanged 
      CurrentCallIndicator indicator = new CurrentCallIndicator(); 
      indicator.IndicatorValue = item["MyValueColumn"]; 

      //Adding to ObservableCollection 
      CallIndicators.Add(indicator); 

     } 
     //Setting Datacontext of a normal TextBlock 
     tbCallsOpen.DataContext = CallIndicators.First(z => z.IndicatorName == "somevalue"); 
    } 
} 

回答

2

你是最有可能的假設變化集合中的標的物將提高CollectionChanged事件;然而那不是ObservableCollection<T>的工作方式。

如果你想要這種行爲,你需要滾動你自己的暗示,並且當在你的收藏中的一個物品內觸發一個PropertyChanged事件時,你需要觸發CollectionChanged事件。

+0

好吧,我現在也添加綁定到ObservableCollection的CollectionChanged事件,仍然沒有喜悅..值更新,但控件不.. – Fox

+0

刪除所有不需要的代碼,如DispatchTimer,看看它是否工作。需要縮小範圍。您也可以檢查輸出窗口。 –

1

您的代碼對我來說看起來或多或少正確,但我不希望您需要使用ObservableCollection <>來獲得您期望的結果:一個簡單的List <>會工作得很好。

如果調試器告訴你DataContext被正確更新爲期望的項目,那麼最可能的問題是如何定義綁定存在問題。如果在調試窗口中沒有發現任何綁定錯誤,那麼我會查看Bea Stollnitz的文章debugging bindings。最特別的,我經常用她提出了「DebugValueConverter」的技術,例如:

/// <summary> 
/// Helps to debug bindings. Use like this: Content="{Binding PropertyName, Converter={StaticResource debugConverter}}" 
/// </summary> 
public class DebugConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     return value; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     return value; 
    } 
} 

然後設置你的轉換器中的斷點,看發生了什麼事。這是一個黑客和混亂,但直到我們都在SL5上(它有內置的綁定調試),這是你最好的選擇。

0

好的,已排序。我自己解決了這個問題。因爲我正在更新循環中的值,所以ObservableCollection未被正確更新。我在數據綁定方法開始時所做的一切就是清除集合:CallIndicators.Clear();

相關問題