我有一个连接到Datatable的Datagrid,它需要加载非常大量的行。
为了加快速度,我加载了10%的行,然后显示表单。大多数情况下,用户只需要那些10%(他们是最近的条目)。在后台线程中,我将剩余的90%的行加载到另一个数据表(SecondData)中。然后我合并两个数据表:
FirstData.BeginLoadData()
FirstData.Merge(SecondData, False)
FirstData.EndLoadData()
这很好用,但Merge操作需要很长时间。如果我反转操作(使用FirstData合并SecondData),则需要的时间要少得多。但是我必须将一个itemsource(SecondData)重新分配给Datagrid,并且用户将丢失当前的滚动位置,选定的行等。
我还尝试从后台线程直接将行添加到FirstData,它似乎工作得很好。但是当我在那之后滚动Datagrid时,我会冻结,并且“DataTable内部索引已损坏”,之后。
这样做的正确方法是什么?
答案 0 :(得分:2)
如果您使用窗口的BeginInvoke方法或控件的Dispatcher属性,则使用它 将委托添加到Dispatcher的事件队列中;但是,你有机会指定一个 它的优先级较低。通过执行一次只加载一个项目的方法,窗口就是 有机会在项目之间执行任何其他更高优先级的事件。这允许 控制或窗口立即显示和渲染,并一次加载一个项目。
以下是一些加载ListBox的示例代码 您可以根据DataGrid进行调整 在这个例子中,我使用了一个ViewModel,它包含一个包含一个对象的ObservableCollection 如果您在转换到DataGrid时遇到问题,我将会返工。
这是Window XAML:
<Window x:Class="ListBoxDragDrop.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Models="clr-namespace:ListBoxDragDrop.Models"
Loaded="Window_Loaded"
Title="Main Window" Height="400" Width="800">
<DockPanel>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ListBox Grid.Column="0" ItemsSource="{Binding Path=MyData}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type Models:Person}">
<StackPanel>
<TextBlock Text="{Binding Name}" ></TextBlock>
<TextBlock Text="{Binding Description}" ></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</DockPanel>
</Window>
以下是带有Loaded事件的Window代码隐藏:
public partial class MainView : Window
{
MainViewModel _mwvm = new ViewModels.MainViewModel();
ObservableCollection<Person> _myData = new ObservableCollection<Person>();
public MainView()
{
InitializeComponent();
this.DataContext = _mwvm;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// Execute a delegate to load
// the first number on the UI thread, with
// a priority of Background.
this.Dispatcher.BeginInvoke(DispatcherPriority.Background, new LoadNumberDelegate(LoadNumber), 1);
}
// Declare a delegate to wrap the LoadNumber method
private delegate void LoadNumberDelegate(int number);
private void LoadNumber(int number)
{
// Add the number to the observable collection
// bound to the ListBox
Person p = new Person { Name = "Jeff - " + number.ToString(), Description = "not used for now"};
_mwvm.MyData.Add(p);
if (number < 10000)
{
// Load the next number, by executing this method
// recursively on the dispatcher queue, with
// a priority of Background.
//
this.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new LoadNumberDelegate(LoadNumber), ++number);
}
}
}
这是ViewModel:
public class MainViewModel : ViewModelBase
{
public MainViewModel()
{
}
private ObservableCollection<Person> _myData = new ObservableCollection<Person>();
public ObservableCollection<Person> MyData
{
get
{
return _myData;
}
set
{
_myData = value;
OnPropertyChanged("MyData");
}
}
}
对于完全性的人的定义:
public class Person
{
public string Name { get; set; }
public string Description { get; set; }
}
答案 1 :(得分:2)
这是一个有点被黑的附加版本,它显示了如何使用仍然使用BeginInvoke绑定到DataView时加载DataGrid。 代码仍然一次加载一行到DataGrid中。 您需要根据需要进行修改;我使用Loaded事件从AdventureWorks示例加载。
以下是ViewModel的工作原理:
这是窗口:
<Window x:Class="DatagridBackgroundWorker.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:WpfToolkit="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"
Loaded="Window_Loaded"
Title="Main Window" Height="400" Width="800">
<DockPanel>
<Grid>
<WpfToolkit:DataGrid
Grid.Column="1"
SelectedItem="{Binding Path=SelectedGroup, Mode=TwoWay}"
ItemsSource="{Binding Path=GridData, Mode=OneWay}" >
</WpfToolkit:DataGrid>
</Grid>
</DockPanel>
</Window>
以下是带有Loaded事件的Window代码隐藏:
public partial class MainView : Window
{
ViewModels.MainViewModel _mvm = new MainViewModel();
public MainView()
{
InitializeComponent();
this.DataContext = _mvm;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Dispatcher d = this.Dispatcher;
_mvm.LoadData(d);
}
}
这里是ViewModel:
public class MainViewModel : ViewModelBase
{
public MainViewModel()
{
// load the connection string from the configuration files
_connectionString = ConfigurationManager.ConnectionStrings["AdventureWorks"].ConnectionString;
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
// load no data 1=0, but get the columns...
string query =
"SELECT [BusinessEntityID],[Name],[SalesPersonID],[Demographics],[rowguid],[ModifiedDate] FROM [Sales].[Store] Where 1=0";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(_ds);
}
}
// only show grid data after button pressed...
private DataSet _ds = new DataSet("MyDataSet");
public DataView GridData
{
get
{
return _ds.Tables[0].DefaultView;
}
}
private void AddRow(SqlDataReader reader)
{
DataRow row = _ds.Tables[0].NewRow();
for (int i = 0; i < reader.FieldCount; i++)
{
row[i] = reader[i];
}
_ds.Tables[0].Rows.Add(row);
}
public void LoadData(Dispatcher dispatcher)
{
// Execute a delegate to load the first number on the UI thread, with a priority of Background.
dispatcher.BeginInvoke(DispatcherPriority.Background, new LoadNumberDelegate(LoadNumber), dispatcher, true, 1);
}
// Declare a delegate to wrap the LoadNumber method
private delegate void LoadNumberDelegate(Dispatcher dispatcher, bool first, int id);
private void LoadNumber(Dispatcher dispatcher, bool first, int id)
{
try
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
// load first 10 rows...
String query = string.Empty;
if (first)
{
// load first 10 rows
query =
"SELECT TOP 10 [BusinessEntityID],[Name],[SalesPersonID],[Demographics],[rowguid],[ModifiedDate] FROM [AdventureWorks2008].[Sales].[Store] ORDER By [BusinessEntityID]";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
int lastId = -1;
SqlDataReader reader = cmd.ExecuteReader();
if (reader != null)
{
if (reader.HasRows)
{
while (reader.Read())
{
lastId = (int)reader["BusinessEntityID"];
AddRow(reader);
}
}
reader.Close();
}
// Load the remaining, by executing this method recursively on
// the dispatcher queue, with a priority of Background.
dispatcher.BeginInvoke(DispatcherPriority.Background,
new LoadNumberDelegate(LoadNumber), dispatcher, false, lastId);
}
else
{
// load the remaining rows...
// SIMULATE DELAY....
Thread.Sleep(5000);
query = string.Format(
"SELECT [BusinessEntityID],[Name],[SalesPersonID],[Demographics],[rowguid],[ModifiedDate] FROM [Sales].[Store] Where [BusinessEntityID] > {0} ORDER By [BusinessEntityID]",
id);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
SqlDataReader reader = cmd.ExecuteReader();
if (reader != null)
{
if (reader.HasRows)
{
while (reader.Read())
{
AddRow(reader);
}
}
reader.Close();
}
}
}
}
catch (SqlException ex)
{
}
}
private string _connectionString = string.Empty;
public string ConnectionString
{
get { return _connectionString; }
set
{
_connectionString = value;
OnPropertyChanged("ConnectionString");
}
}
}