在wpf应用程序中打开视图时的延迟
我们正在开发使用WPF,物料设计和MS-Access 2007作为后端的应用程序。现在我们面临着打开单一视图时应用程序放慢的问题,那个特定的视图有16个组合的填充。它需要7秒钟的过程,以下用于绑定组合框项目源在wpf应用程序中打开视图时的延迟
List<ComboBind> values = new List<ComboBind>();
try
{
using (var oleDbCommand = new OleDbCommand())
{
oleDbCommand.CommandText = query ;
oleDbCommand.Connection = Connection.con;
var sql = query;
var oleDbDataReader = oleDbCommand.ExecuteReader();
while (oleDbDataReader.Read())
{
ComboBind b = new ComboBind();
b.id = oleDbDataReader[0].ToString().ToInt();
b.name = oleDbDataReader[1].ToString();
values.Add(b);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
它看起来像你想查看在初始化时加载UI线程的数据,这是问题的原因代码。要么在后台线程中加载数据,要么在打开视图之前执行它。在单独的任务
简单的代码片段加载数据:
//Might be your view code behind or
//ViewModel if you are using MVVM
public class ViewCodeBehind
{
public List<ComboBind> ComboItems { get; set; }
public void Initialize()
{
//start bacground task for data loading
var comboQuery = "select *from data";
Task.Run(() => LoadItems(comboQuery));
}
public void LoadItems(string query)
{
List<ComboBind> values = new List<ComboBind>();
try
{
using (var oleDbCommand = new OleDbCommand())
{
oleDbCommand.CommandText = query;
oleDbCommand.Connection = Connection.con;
var sql = query;
var oleDbDataReader = oleDbCommand.ExecuteReader();
while (oleDbDataReader.Read())
{
ComboBind b = new ComboBind();
b.id = oleDbDataReader[0].ToString().ToInt();
b.name = oleDbDataReader[1].ToString();
values.Add(b);
}
}
//use dispatcher to pass data back to UI thread
System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvoke(
new Action(() =>
{
ComboItems = values;
}));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
感谢你@Skobarx快速回复在WPF中新的刚刚开始MVVM,所以你可以解释我怎么可以避免 –
@SachinJadhav,你是什么意思“避免”?如果你的意思是在数据加载期间出现延迟,那么答案将超出这个话题。 – Skobarx
System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvoke( new Action(()=> { ComboItems = values; }));伟大的作品... 2秒内打开的视图谢谢你的帮助 –
第1步:刻录下来'Access'它是纯粹的邪恶的源泉! 第2步。发布你的ComboBox的xaml。 我希望你省略'INotifyPropertyChanged'实现。 – XAMlMAX
即时通讯使用FilteredComboBox派生自组合框类 –
有两种可能性:** 1 **您对数据库的查询需要很长时间或** 2 **在没有启用“Virtualization”的情况下显示很多记录,导致应用程序创建大量“U”个项目。现在由你来找出你的情况。你也可以把这些代码放在你的文章中。 – XAMlMAX