![](/img/trans.png)
[英]Removing items from a observablecollection bound to a datagrid Silverlight?
[英]DataGrid not updating when items added to ObservableCollection in Silverlight
我有一個與WCF服務交互的Silverlight應用程序。 它定期從此服務接收要添加到列表的新項目,並且每個新元素都添加到ObservableCollection的末尾(每個新元素的collection.Add())。
項目本身一旦接收就不會更改,並且項目的類會繼承INotifyPropertyChanged,但是當我添加新項目(從WCF接收)時,DataGrid不會更新。
我還為DataGrid綁定使用了自定義格式化程序,但是我認為這是沒有問題的,因為初始項集正確顯示(首次設置ItemsSource時)。
我已經希望新的元素出現,因為我已經確認ObservableCollection發出了正確的add事件。 由於ObservableCollection繼承自INotifyCollectionChanged,因此是否不更新DataGrid?
到目前為止,我發現的唯一解決方案是:
dataGrid.ItemsSource = null;
dataGrid.ItemsSource = collection;
關於如何進行更新的任何想法? 此方法在相當長的時間內阻塞了UI。
謝謝
更新:代碼
在WCF回調事件中將元素展開和提取:
// The ItemWrapper allows the Binding converter to be passed the entire trade object, rather than just each property.
ObservableCollection<ItemWrapper<ExpandedTrade>> pastTrades = new ObservableCollection<ItemWrapper<ExpandedTrade>>();
....
// Extract and expand data - MinimalTrade is the data sent through WCF
var convertedTrades = from MinimalTrade t in e.trades
select new ItemWrapper<ExpandedTrade>(
new ExpandedTrade(t,
usernames.ContainsKey(t.UserToId) ? usernames[t.UserToId] : null, potentialWealth != null ? potentialWealth.CurrentWealth : null)); // Get name, otherwise null.
// Data now expanded (to show full information like usernames
// pastTrades is an observableCollection
foreach (var trade in convertedTrades)
{
pastTrades.Add(trade);
}
OnNewMyTradeHistory(pastTrades);
然后,OnNewMyTradeHistory事件將執行以下操作:
if (tradeHistory.ItemsSource == null) tradeHistory.ItemsSource = trades;
這只會將ItemsSource設置一次(到ObservableCollection),並且將觸發添加事件,但是UI端沒有任何反應。
WCF回調可能在另一個線程中發生。
我找到了解決方案!
我已經在ItemWrapper和ExpandedTrade中實現了Equals
, GetHashCode
和ToString
方法:
ItemWrapper.cs :(在子類中調用等效方法)
public override bool Equals(object obj)
{
if(obj is T) return Quote.Equals(obj);
if (obj is ItemWrapper<T>) return Quote.Equals(((ItemWrapper<T>)obj).Quote);
return this == obj;
}
public override int GetHashCode() { return Quote.GetHashCode(); }
public override string ToString() { return Quote.ToString(); }
ExpandedTrade.cs:
public override bool Equals(object obj)
{
if (obj == null) return false;
ExpandedQuote q = obj as ExpandedQuote;
if (q == null) return false;
return q.Id == Id;
}
public override int GetHashCode() { return Id; }
刪除這些方法后,它開始起作用。 我以為DataGrid正在某處測試是否相等,並且某種原因返回了錯誤的測試。 這些ID是唯一的,但是現在通過使用默認的相等性測試(通過引用),它現在可以工作。
告訴我這個流程是否正確:
還是pastTrades是僅初始化一次的字段? 括號和方法界限會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.