[英]WPF Silverlight Datagrid in real time, refresh? Timer?
我有一些數據網格,我需要“刷新”每個...讓我們說1分鍾。
計時器是最好的選擇嗎?
public PageMain()
{
InitializeComponent();
DataGridFill();
InitTimer();
}
private void InitTimer()
{
disTimer = new Timer(new TimeSpan(0, 1, 0).TotalMilliseconds);
disTimer.Elapsed += disTimer_Elapsed;
disTimer.Start();
}
void disTimer_Elapsed(object sender, ElapsedEventArgs e)
{
DataGridFill();
}
private void DataGridFill()
{
var items = GetItems(1);
ICollectionView itemsView =
CollectionViewSource.GetDefaultView(items);
itemsView.GroupDescriptions.Add(new PropertyGroupDescription("MyCustomGroup"));
// Set the view as the DataContext for the DataGrid
AmbientesDataGrid.DataContext = itemsView;
}
是否有一個不那么“臟”的解決方案?
“刷新” DataGrid
的最佳方法是將其綁定到項目集合,並每隔X分鍾更新一次項目的源集合。
<DataGrid ItemsSource="{Binding MyCollection}" ... />
這樣您就不必引用DataGrid
本身,因此您的UI邏輯和應用程序邏輯保持分離,如果您的刷新需要一段時間,您可以在后台線程上運行它而不會鎖定您的UI。
因為WPF無法更新從另一個線程在一個線程上創建的對象,所以您可能希望獲取數據並將其存儲在后台線程上的臨時集合中,然后在主UI線程上更新綁定集合。
對於時序位,如果需要,請使用Timer
或DispatcherTimer
。
var timer = new System.Windows.Threading.DispatcherTimer();
timer.Tick += Timer_Tick;
timer.Interval = new TimeSpan(0,1,0);
timer.Start();
private void Timer_Tick(object sender, EventArgs e)
{
MyCollection = GetUpdatedCollectionData();
}
我的首選方法:
public sealed class ViewModel
{
/// <summary>
/// As this is readonly, the list property cannot change, just it's content so
/// I don't need to send notify messages.
/// </summary>
private readonly ObservableCollection<T> _list = new ObservableCollection<T>();
/// <summary>
/// Bind to me.
/// I publish as IEnumerable<T>, no need to show your inner workings.
/// </summary>
public IEnumerable<T> List { get { return _list; } }
/// <summary>
/// Add items. Call from a despatch timer if you wish.
/// </summary>
/// <param name="newItems"></param>
public void AddItems(IEnumerable<T> newItems)
{
foreach(var item in newItems)
{
_list.Add(item);
}
}
/// <summary>
/// Sets the list of items. Call from a despatch timer if you wish.
/// </summary>
/// <param name="newItems"></param>
public void SetItems(IEnumerable<T> newItems)
{
_list.Clear();
AddItems(newItems);
}
}
不喜歡在ObservableCollection<T>
缺少像樣的AddRange
/ ReplaceRange
? 我也不是,但這里是ObservableCollection<T>
的后代,以添加消息高效的AddRange
,以及單元測試:
ObservableCollection不支持AddRange方法,因此除了INotifyCollectionChanging外,我還會收到添加的每個項目的通知?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.