2015-08-27 58 views
0

我有一個包含幾個名稱 - 值對的DataGrid,所述名稱 - 值對從硬件設備輪詢。爲了提高性能(輪詢循環而不是UI)我想知道綁定的哪些項目被顯示。DataGrid只更新顯示的行

<DataGrid Grid.Row="1" ItemsSource="{Binding ParameterViewSource.View}" 
AutoGenerateColumns="False" CanUserReorderColumns="False"/> 

DataGrid現在可以默認虛擬化行。但是對於我的後臺輪詢循環,我想知道我的CollectionViewSource的哪些項目目前在RowPresenter中。

該方法應該可以在MVVM中實現。

我試圖使用DataGridRowsPresenter - 和兒童(或更具體的DataContext),但我無法得到有關更改的通知。有沒有什麼簡單的方法來實現我想要的。

private static void GridOnLoaded(object sender, RoutedEventArgs routedEventArgs) 
     { 
      DataGrid grid = (DataGrid)sender; 
      var rowPresenter = grid.FindChildRecursive<DataGridRowsPresenter>(); 

      var items = rowPresenter.Children.OfType<DataGridRow>() 
      .Select(x => x.DataContext); 
      //Works but does not get notified about changes to the Children 
      //collection which occure if i resize the Grid, Collapse a 
      //Detail Row and so on 
     } 
+0

你能否給我們提供一些代碼 –

回答

0

我解決了這個使用附加屬性:

public class DataGridHelper 
{ 
    //I skipped the attached Properties (IsAttached, StartIndex and Count) declarations   


    private static void IsAttachedPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args) 
    { 
     DataGrid grid = (DataGrid)dependencyObject; 
     grid.Loaded += GridOnLoaded; 
    } 

    private static void GridOnLoaded(object sender, EventArgs eventArgs) 
    { 
     DataGrid grid = (DataGrid)sender; 
     ScrollBar scrollBar = grid.FindChildRecursive<ScrollBar>("PART_VerticalScrollBar"); 

     if (scrollBar != null) 
     { 
      scrollBar.ValueChanged += (o, args) => SetVisibleItems(grid, scrollBar); 

      DependencyPropertyDescriptor descriptor = DependencyPropertyDescriptor.FromProperty(RangeBase.MaximumProperty, typeof (ScrollBar)); 
      descriptor.AddValueChanged(scrollBar, (o, args) => SetVisibleItems(grid, scrollBar)); 

      SetVisibleItems(grid, scrollBar); 
     } 
    } 

    private static void SetVisibleItems(DataGrid grid, ScrollBar scrollBar) 
    { 
     int startIndex = (int)Math.Floor(scrollBar.Value); 
     int count = (int)Math.Ceiling(grid.Items.Count - scrollBar.Maximum); 

     SetStartIndex(grid, startIndex); 
     SetCount(grid, count); 
    } 

,然後使用OneWayToSource束縛我的DataGrid的附加屬性一些視圖模型屬性。

<DataGrid Grid.Row="1" ItemsSource="{Binding ParameterViewSource.View}" AutoGenerateColumns="False" CanUserReorderColumns="False" 
        userInterface:DataGridHelper.IsAttached="True" 
        userInterface:DataGridHelper.Count="{Binding Path=Count, Mode=OneWayToSource}" 
        userInterface:DataGridHelper.StartIndex="{Binding Path=StartIndex, Mode=OneWayToSource}"> 

您還可以處理DataGrid上的Count和StartIndex,並提取Items屬性的SubArray。