一个wpf异步绑定数据的例子

        DataTable dt = new DataTable("Info");
        delegate void BindDataAsync();
        GridView gv = new GridView();
private void btnLoad_Click(object sender, RoutedEventArgs e)
        {
            BeginBindData();
        }
 #region Invoke the Binding Data method asynchorously
        private void BeginBindData()
        {
            BindDataAsync bindData = new BindDataAsync(BindData);
            IAsyncResult iar = bindData.BeginInvoke(new AsyncCallback(EndBindData), bindData);
            tsStatus.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
            {
                tsStatus.Content = "正在加载中。。。";
            }));
        }

        private void EndBindData(IAsyncResult iar)
        {
            tsStatus.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
            {
                tsStatus.Content = "加载完毕。。。";
            }));
            BindDataAsync bindData = (BindDataAsync)iar.AsyncState;
            bindData.EndInvoke(iar);
        }

        private void BindData()
        {

            GetHeader();
            DataTable dt = LoadData();

            tsStatus.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
            {
                tsStatus.Content = "正在绑定数据,请稍候。。。";
            }));

            //using Dispatcher to avoid crossing thread exception
            listView1.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
            {
               
                foreach (DataColumn item in dt.Columns)
                {
                    GridViewColumn gvc = new GridViewColumn();
                    gvc.DisplayMemberBinding = new Binding(item.ColumnName);
                    gvc.Header = item.ColumnName;
                    gv.Columns.Add(gvc);
                }

                listView1.View = gv;
                listView1.DataContext = dt;
                listView1.SetBinding(ListView.ItemsSourceProperty, new Binding());  //must add this , otherwise it will not be showen

               
            }));
        }
        #endregion

        #region Initialize the DataTable

        private void GetHeader()
        {
            DataColumn dc = new DataColumn();
            dc.ColumnName = "name";
            dt.Columns.Add(dc);
           

        }

        private DataTable LoadData()
        {

                for (int i = 1; i < 10000; i++)
                {
                    DataRow dr = dt.NewRow();
                    dr[0] = i.ToString();
                    tsStatus.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                    {
                        tsStatus.Content = "当前已经加载" + i + "条数据。。。";
                    }));
                    dt.Rows.Add(dr);
                }
            return dt;
        }

        #endregion

  

posted @ 2012-06-26 00:12  lhx880619  阅读(2940)  评论(0编辑  收藏  举报