在非UI线程上修改ObservableCollection,那么UI可能不会自动更新
public ObservableCollection<txt_log> Logs = new ObservableCollection<txt_log>();
txtLog.ItemsSource = Logs;
void deviceDataRec(CCCD.MsgObjTypeDef msg, out CCCD.MsgObjTypeDef return_msg)
{
var newLog = new VRAM.devLog(msg.data);
#region 系统日志记录 -接收
StaticClass.SentData =
"收的时间:" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.ff")
+ " 接收数量: " + receiveCount
+ " log ID:" + newLog.log_devId
+ " 延迟时间:" + (DateTime.Now - StaticClass.sendtime).TotalMilliseconds + "ms"
;
StaticClass.SentID = newLog.log_devId;
StaticClass.ReceiveCount = receiveCount;
StaticClass.DelayTime = (DateTime.Now - StaticClass.sendtime).TotalMilliseconds;
txt_log txt_Log_sent = new txt_log();
txt_Log_sent.devInfo = StaticClass.SentData;
syslogsPage.Logs.Add(txt_Log_sent); //没有在UI线程上
receiveCount++;
}
txt_Log_sent有数据增加,但是界面没有变化。要确保所有对集合的修改都在UI线程上执行。你可以使用Dispatcher.Invoke
或Dispatcher.BeginInvoke
来确保代码在UI线程上执行。
public ObservableCollection<txt_log> Logs = new ObservableCollection<txt_log>();
txtLog.ItemsSource = Logs;
void deviceDataRec(CCCD.MsgObjTypeDef msg, out CCCD.MsgObjTypeDef return_msg)
{
var newLog = new VRAM.devLog(msg.data);
#region 系统日志记录 -接收
StaticClass.SentData =
"收的时间:" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.ff")
+ " 接收数量: " + receiveCount
+ " log ID:" + newLog.log_devId
+ " 延迟时间:" + (DateTime.Now - StaticClass.sendtime).TotalMilliseconds + "ms"
;
StaticClass.SentID = newLog.log_devId;
StaticClass.ReceiveCount = receiveCount;
StaticClass.DelayTime = (DateTime.Now - StaticClass.sendtime).TotalMilliseconds;
txt_log txt_Log_sent = new txt_log();
txt_Log_sent.devInfo = StaticClass.SentData;
// 使用Dispatcher确保在UI线程上执行
Application.Current.Dispatcher.Invoke(() =>
{
// 将txt_Log对象添加到绑定的ObservableCollection中
Logs.Add(txt_Log);
});
receiveCount++;
}