我遇到了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