简体   繁体   English

DataGrid新的DataContext之后的事件

[英]Event after DataGrid new DataContext

in my WPF Window I have DataGrid . 在我的WPF窗口中,我有DataGrid
DataGrid loads data from DataTable like: DataGrid从DataTable加载数据,如下所示:

gridData.DataContext = dataTable

All works fine, DataGrid is filled by data from Stored procedure by Data Table. 一切正常, DataGrid由数据表中的存储过程中的数据填充。 Depends on kind of data, Columns of DataGrid has different Width and I want get this Widths AFTER DataGrid is filled by data. 取决于数据的类型,DataGrid的列具有不同的宽度,我想在数据网格填充数据后获得此宽度。 Which event I have to handle to do this? 我必须处理哪个事件? I tried DataContextChanged , Loaded , AutoGenratedColumns , SourceUpdated - but all of them seems to be called before DataGrid is filled by data. 我尝试了DataContextChangedLoadedAutoGenratedColumnsSourceUpdated ,但是似乎所有这些都在DataGrid填充数据之前被调用。

Any solution? 有什么办法吗?

You can use several approaches to catch the moment when DataGrid's ItemsSource is changed: 您可以使用几种方法来捕捉DataGrid的ItemsSource更改的时刻:

  1. Use DependencyPropertyDescriptor: 使用DependencyPropertyDescriptor:

      DependencyPropertyDescriptor itemsSourcePropertyDescriptor = DependencyPropertyDescriptor.FromProperty(ItemsControl.ItemsSourceProperty, typeof(DataGrid)); itemsSourcePropertyDescriptor.AddValueChanged(dataGrid1, OnDataGridItemsSourceChanged); private void OnDataGridItemsSourceChanged(object sender, EventArgs e) { } 
  2. Create a DataGrid descendant and override the OnItemsSourceChanged method 创建一个DataGrid后代并重写OnItemsSourceChanged方法

There is no bulletproof way as the DataGrid doesn't raise any "columns generated" event but you should be able to call Dispatcher.Invoke with a DispatcherPriority lower than DispatcherPriority.Loaded once the DataGrid has been loaded, eg: 有是无防弹方法DataGrid不会引发任何“列中产生”事件,但你应该能够调用Dispatcher.InvokeDispatcherPriority低于DispatcherPriority.Loaded一旦DataGrid已被加载,例如:

dataGrid.AutoGenerateColumns = true;
dataGrid.ItemsSource = new List<Item> { new Item() { Name = "some very long name..." } };
dataGrid.Loaded += (s, e) => 
{
    dataGrid.Dispatcher.Invoke(new Action(() =>
    {
        MessageBox.Show(dataGrid.Columns[0].ActualWidth.ToString());
    }), System.Windows.Threading.DispatcherPriority.Input);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM