項目需要一個硬件檢測功能,需要用到界面刷新,剛開始想用個定時器,對檢測過的硬設定時添加後刷新 界面。
但是很遺憾,定時器並不能進行刷新。後台檢測List數據裡面已經添加了很多了很多數據了, 就是不能顯示到界面然後百度一下“WPF刷新界面”找了好幾篇文章,大致都是如下代碼:
public class UIHelper : Application
{
//刷新界面
private static DispatcherOperationCallback
exitFrameCallback = new DispatcherOperationCallback(ExitFrame);
public static void DoEvents()
{
DispatcherFrame nestedFrame = new DispatcherFrame();
DispatcherOperation exitOperation =
Dispatcher.CurrentDispatcher.BeginInvoke(
DispatcherPriority.Background,
exitFrameCallback, nestedFrame);
Dispatcher.PushFrame(nestedFrame);
if (exitOperation.Status != DispatcherOperationStatus.Completed)
{
exitOperation.Abort();
}
}
private static object ExitFrame(object state)
{
DispatcherFrame frame = state as DispatcherFrame;
frame.Continue = false;
return null;
}
}
我把代碼手敲下來,(注意不是復制,應為我不是太懂,這裡也勸大家不要輕易復制,因為復 制就算解決問題了下次你還是不知道怎麼回事)。在我添加數據後面調用UIHelper .DoEvents(),但是還是沒 有反應。依然不刷新,我就郁悶了,別人可以解決為啥到我這就不能用了呢,請教各位大神,這個怎麼用啊? 有什麼前提條件嗎?請我告訴我……
然後繼續找啊找啊,在CSDN上找到了類似的問題。原來 list<T>沒有數據更新的功能,這裡面需要用 ObservableCollection<T> 類 或 BindingList<T> 類 代替 List 類,看ObservableCollection<T>在幫助文檔裡的說明,這個提 供自動更新數據的接口,可以自動向控件發送更新消息,果斷一實驗。OK成功顯示。
public partial class Window2 : Window
{
DispatcherTimer _mainTimer;
public Window2()
{
InitializeComponent();
_mainTimer = new DispatcherTimer();
_mainTimer.Interval = TimeSpan.FromSeconds(1);
_mainTimer.Tick += new EventHandler(_mainTimer_Tick);
_mainTimer.IsEnabled = true;
}
void _mainTimer_Tick(object sender, EventArgs e)
{
if (progressBar1.Value == progressBar1.Maximum)
progressBar1.Value = 0;
progressBar1.Value++;
DeviceCheckInfo device = new DeviceCheckInfo();
device.CheckResult = true;
device.Name = "發卡器" + progressBar1.Value;
device.CheckContent = "打卡短短";
Dispatcher.BeginInvoke(new Action(() => {
if (list != null)
list.Add(device);
lbtest.ItemsSource = list;
// UIHelper.DoEvents();
}));
}
ObservableCollection<DeviceCheckInfo> list;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
list = new ObservableCollection<DeviceCheckInfo>(){
new DeviceCheckInfo {Name="三合一讀卡器",CheckContent="duankou",CheckResult=true },
new DeviceCheckInfo {Name="發卡器",CheckContent="tongdao",CheckResult=false },
new DeviceCheckInfo {Name="打印機",CheckContent="youzhi" ,CheckResult=true}
};
lbtest.ItemsSource = list;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
DeviceCheckInfo device = new DeviceCheckInfo();
device.CheckResult = true;
device.Name = "發卡器" + progressBar1.Value;
device.CheckContent = "打卡短短";
list.Add(device);
lbtest.ItemsSource = list;
}
}
效果如下:
