我遇到了ObservableCollection獲取新項目但未反映ListView中的這些更改的問題。我在實施這個方法時有足夠的怪癖,我很難確定問題所在。ObservableCollection <T>不更新UI
我的ObservableCollection正是如此實現:
public class MessageList : ObservableCollection<LobbyMessage>
{
public MessageList(): base()
{
Add(new LobbyMessage() { Name = "System", Message = "Welcome!" });
}
}
我存儲在一個靜態屬性集合(以便其從多個用戶控件方便):
static public MessageList LobbyMessages { get; set; }
在的onload事件我main NavigationWindow我有以下行:
ChatHelper.LobbyMessages = new MessageList();
我的X AML在ListView中位於該用戶控件讀作:
<ListBox IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Mode=OneWay}"
x:Name="ListBoxChatMessages"
d:UseSampleData="True"
ItemTemplate="{DynamicResource MessageListTemplate}"
IsEnabled="True">
<ListBox.DataContext>
<Magrathea_Words_Tools:MessageList/>
</ListBox.DataContext>
</ListBox>
我在構造添加的初始消息在UI顯示就好了。
現在,我向集合中添加新項目的方式來自於來自WCF服務的CallBack。我有這個代碼在WinForms應用程序中工作,並且需要將回調調入UI線程,所以我留下了該代碼。下面是該方法的一個簡化版本:
Helper.Context = SynchronizationContext.Current;
#region IServiceMessageCallback Members
/// <summary>
/// Callback handler for when the service has a message for
/// this client
/// </summary>
/// <param name="serviceMessage"></param>
public void OnReceivedServiceMessage(ServiceMessage serviceMessage)
{
// This is being called from the WCF service on it's own thread so
// we have to marshall the call back to this thread.
SendOrPostCallback callback = delegate
{
switch (serviceMessage.MessageType)
{
case MessageType.ChatMessage:
ChatHelper.LobbyMessages.Add(
new LobbyMessage()
{
Name = serviceMessage.OriginatingPlayer.Name,
Message = serviceMessage.Message
});
break;
default:
break;
}
};
Helper.Context.Post(callback, null);
}
在調試我可以看到越來越採集與服務的消息更新,但是UI沒有反映這些補充。
有關我缺少什麼來獲取ListView以反映集合中的這些新項目的任何想法?
據我所知,MS在WPF意圖是使事情,如設置結合源(像ItemsSource屬性)的靜態數據設置在XAML,而不是在代碼。 一位更有經驗的開發人員重拍我的複雜程序,幾乎沒有C#,只有更多的xaml。 xaml> code。 – 2008-12-09 14:46:07