DataGrid仅更新显示的行

时间:2015-08-27 14:19:00

标签: wpf binding datagrid

我有一个包含一些名称 - 值对的DataGrid,所述名称 - 值对从硬件设备中轮询。为了提高性能(不是UI的轮询循环),我想知道哪些项目的绑定被显示。

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

DataGrid现在默认情况下虚拟化行。但是对于我的后台轮询循环,我想知道我的CollectionViewSource当前在RowPresenter中的哪些项目。

该方法应该可以在MVVM中实现。

我尝试使用DataGridRowsPresenter - 和Children(或更具体的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
        }

1 个答案:

答案 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。