該修改的ObeservableCollection是我previous question 這裏是我的mainwindow.cs綁定WPF控件由一個後臺線程
public partial class MainWindow : Window
{
ObservableCollection<string> store;
public MainWindow()
{
SerialPort _serialPort = new SerialPort(SerialCom.findCOMPort(), 115200, Parity.None, 8, StopBits.One);
_serialPort.Handshake = Handshake.None;
string[] query = new string[3] { "t02", "t03", "t04" };
store = new ObservableCollection<string> { " ", " ", " " };
this.DataContext = this;
Thread thread = new Thread(delegate(){Process(store,query,_serialPort);});
thread.IsBackground = true;
try
{
thread.Start(); //catch sudden serial port closure exception
}
catch (Exception)
{
thread.Abort();
}
}
public static void Process(ObservableCollection<string> store, string[] query, SerialPort _serialPort)
{
while (true)
{
for (int i = 0; i < 3; i++)
{
string add = SerialCom.returnData(query[i], _serialPort);
if (store[i] != add)
{
store.Insert(i,add);
}
}
Thread.Sleep(300);
}
}
我有我的XAML頁面中的WPF ListView控件的延續。我想將該控件綁定到在非UI線程中更改的ObservableCollection。這似乎是美中不足的是我在程序運行時必須查詢設備的無限循環。另外,由於ObservableCollection實現了INotifyPropertyChanged,因此當我將集合綁定到控件時,控件應該自動更新而不用任何其他代碼在代碼後面還是XAML?
當您將observablecollection綁定到listview時,它由UI線程所擁有。如果你想更新集合,我認爲你需要使用Dispatcher.BeginInvoke,一切都會好的。 – MrEdge