【问题标题】:WPF DataGrid ItemSource Refresh - GridColumns shows strange behaviourWPF DataGrid ItemSource Refresh - GridColumns 显示奇怪的行为
【发布时间】:2011-10-10 11:12:32
【问题描述】:

我正在开发基于 WPF DataGrid 的 WPF UserControl,以支持使用我们自己的基于业务的上下文菜单生成动态列。

我创建了名为 DataSource 的依赖属性,当我设置 DataSource 时调用自定义方法将我的 dataSource 绑定到动态创建列并设置 ItemSource 属性。第一次一切正常。我有一个名为 Refresh 的上下文菜单,当用户单击 Refresh 时,SQL 将执行并且上述操作的相同循环将发生。在第二次中,完美地创建了行和列。但是当我做水平滚动时,列标题没有正确显示,它在滚动时会失去它们的视觉状态。

我的自定义属性 - 数据源

 public static DependencyProperty DataSourceProperty =
      DependencyProperty.Register("DataSource", typeof(GridDataModel), typeof(MyGridView),
      new PropertyMetadata((dependencyObject, eventArgs) =>
      {
          if (eventArgs.OldValue != null)
          {
              ((GridDataModel)eventArgs.OldValue).Dispose();
          }
          BindToDataSource((MyGridView)dependencyObject, (GridDataModel)eventArgs.NewValue);              
      }));

每次设置 DataSource 属性时都会调用的自定义方法:

 private static void BindToDataSource(MyGridView view, GridDataModel dataModel)
    {
        if (view.ViewModel != null)
        {               
            BindingOperations.ClearAllBindings(view.GridView);
            view.GridView.Items.Clear();                
            view.GridView.Columns.Clear();                
            view.GridView.ItemsSource = null;                
            view.ViewModel.Dispose();                
        }
        view.ViewModel = new MyGridViewModel(dataModel);
        view.ViewModel.PrepareGridView();
        view.LayoutRoot.DataContext = view.ViewModel;
        view.CreateColumns();                        
        view.GridView.SetBinding(DataGrid.ItemsSourceProperty, new Binding("DisplayRows"));
    }

我在刷新菜单点击时调用的以下代码:

    private void OnRefreshClick(object sender, RoutedEventArgs e)
    {
        var data = new TestDataAccess();
       DataSource = data.MakeGridModel("select  Top 200 * from ApplicationUSer"); //Assigning DataSource Again, which will call the above method.
        GridView.UpdateLayout();
    }

刷新后,你会看到水平滚动时列对齐变得奇怪。

尝试使用 GridColumnWidth =0,并再次设置为 Auto,尝试使用 GridView.UpdateLayout()。

【问题讨论】:

    标签: wpf datagrid


    【解决方案1】:

    我自己解决了上述问题。

    我使用了 BindingOperations.ClearAllBindings() 而不是 BindingOperations.ClearBinding(view.GridView, DataGrid.ItemSourceProperty) - 它只清除了 ItemSource,这样我每次绑定数据时都可以通过 Items.Clear() 重新获得内存。

    由于 ClearAllBindings,它也清除了标题面板绑定,因此它失去了 ParentTemplate.Width 属性,因为水平滚动时发生了那个奇怪的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-06
      • 2011-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-30
      • 2018-12-09
      • 1970-01-01
      相关资源
      最近更新 更多