代码之家  ›  专栏  ›  技术社区  ›  Maestro

WPF Datagrid/Datatable:大量行

  •  2
  • Maestro  · 技术社区  · 15 年前

    我有一个连接到Datatable的Datagrid,它需要加载大量的行。

    FirstData.BeginLoadData()
    FirstData.Merge(SecondData, False)
    FirstData.EndLoadData()
    

    这很好,但是合并操作需要很长时间。如果我反转操作(将SecondData与FirstData合并),所花的时间会少得多。但是接下来我必须将itemsource(SecondData)重新分配给Datagrid,并且用户会松开当前的滚动位置、选中的行等。

    我还尝试从后台线程将行直接添加到FirstData中,看起来效果不错。但是当我在那之后滚动Datagrid时,我会被冻结,然后“DataTable internal index is corrupted”。

    正确的方法是什么?

    2 回复  |  直到 15 年前
        1
  •  3
  •   Zamboni    15 年前

    下面是一个有点黑客攻击的附加版本,它展示了如何在使用still BeginInvoke绑定到DataView时加载DataGrid。 代码仍然一次加载一行到DataGrid中。

    以下是ViewModel的工作原理:

    1. 首先使用Where子句为1=0的SQL语句加载列
    2. 呼叫调度器.BeginInvoke首先加载数据子集
    3. 那就打电话调度器.BeginInvoke再次加载剩余数据

    这是窗户:

    <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>
    

    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");
         }
      }
    }
    
        2
  •  3
  •   Zamboni    15 年前

    如果使用窗口或控件Dispatcher属性的BeginInvoke方法,则 将委托添加到Dispatchers事件队列;但是,您可以指定 它的优先级较低。通过执行一次只加载一个项的方法,窗口 控件或窗口,以便立即显示和渲染,并一次加载一个项。

    下面是一些加载列表框的示例代码。
    您可以根据您的数据网格来调整它。

    如果你有困难转换到你的数据网格我会返工。

    下面是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>
    

    下面是加载事件的窗口代码:

    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; }
    }