2017-03-27 55 views
1

我嘗試,如果有更新DataGrid.ItemsSource不結冰如何更新DataGrid.ItemsSource而不凍結?

public static DataTable DataTableAccounts { get; set; } 

這是我從數據庫中獲取(SQLite的)

要在程序中顯示這個數據,我寫

DataGridAccounts.ItemsSource = DataTableAccounts.DefaultView; 

更改DataTableAccounts中的數據後,我更新Data電網

DataGridAccounts.ItemsSource = null; 
DataGridAccounts.ItemsSource = DataTableAccounts.DefaultView; 

但我做每1秒,因爲在DataTableAccounts數據變化太快了。 由於這個更新,我得到了凍結窗口程序。

問題: 如何更新DataGridAccounts.ItemsSource而不凍結?

p.s.我嘗試使用(異步\ aswait)... ItemsSource = {綁定}在XAML代碼...和其他。沒有什麼幫助我。

+0

如果它是WPF,並且您正在使用綁定,則在更新網格時不需要手動刷新UI;那會受到綁定的關注。你有沒有設置你的列綁定? – NoSaidTheCompiler

+0

@NoSaidTheCompiler,MB我只是可以從代碼刷新UI?是的,我設置了列綁定 – skvoshiz

+0

我看到的一個問題是,您將設置整個項目源,如果它是1000行,您將在呈現時執行perf命中。使用綁定,它只會更新更改的屬性,可能會爲您提供更好的性能。我沒有寫一個示例代碼來測試,雖然.. – NoSaidTheCompiler

回答

0

以下示例每隔10秒運行一次後臺服務以更新GUI。你可以隨意修改它。通過將線程作爲異步任務運行,您的GUI永遠不會掛起。

public frm_testform() 
{ 

    InitializeComponent(); 

    dispatcherTimer_Tick().DoNotAwait(); 

} 

private async Task dispatcherTimer_Tick() 
{ 
    DispatcherTimer timer = new DispatcherTimer(); 
    TaskCompletionSource<bool> tcs = null; 
    EventHandler tickHandler = (s, e) => tcs.TrySetResult(true); 

    timer.Interval = TimeSpan.FromSeconds(10); 
    timer.Tick += tickHandler; 
    timer.Start(); 

    while (true) 
    { 
     tcs = new TaskCompletionSource<bool>(); 

     await Task.Run(() => 
     { 
     // Run your background service and UI update here 
     await tcs.Task; 
    } 

} 
0

你正在努力工作。您只需將數據網格項源設置爲數據表。

DataGridAccounts.ItemsSource = DataTableAccounts;

隨着數據表的變化,網格會更新。