How can I get a DataGrid to scroll smoothly when the Row is taller than the Viewport?

后端 未结 2 1901
忘掉有多难
忘掉有多难 2020-12-15 11:38

I have a DataGrid full of notes, and it\'s possible that a note will be taller then the DataGrid\'s height. When this happens, if you try and scroll down to read the bottom

相关标签:
2条回答
  • 2020-12-15 12:25

    I believe you are looking for the VirtualizingPanel.ScrollUnit attached property which you can set on the DataGrid.

    If you set its value to Pixel instead of the default Item, it should do what you want.

    0 讨论(0)
  • 2020-12-15 12:33

    If you don't want to upgrade to .NET 4.5, you can still set the IsPixelBased property on the underlying VirtualizingStackPanel. However this property is internal in .NET 4.0, so you will have to do that through reflection.

    public static class VirtualizingStackPanelBehaviors
    {
        public static bool GetIsPixelBasedScrolling(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsPixelBasedScrollingProperty);
        }
    
        public static void SetIsPixelBasedScrolling(DependencyObject obj, bool value)
        {
            obj.SetValue(IsPixelBasedScrollingProperty, value);
        }
    
        // Using a DependencyProperty as the backing store for IsPixelBasedScrolling.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsPixelBasedScrollingProperty =
            DependencyProperty.RegisterAttached("IsPixelBasedScrolling", typeof(bool), typeof(VirtualizingStackPanelBehaviors), new UIPropertyMetadata(false, OnIsPixelBasedScrollingChanged));
    
        private static void OnIsPixelBasedScrollingChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            var virtualizingStackPanel = o as VirtualizingStackPanel;
            if (virtualizingStackPanel == null)
                throw new InvalidOperationException();
    
            var isPixelBasedPropertyInfo = typeof(VirtualizingStackPanel).GetProperty("IsPixelBased", BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.NonPublic);
            if (isPixelBasedPropertyInfo == null)
                throw new InvalidOperationException();
    
            isPixelBasedPropertyInfo.SetValue(virtualizingStackPanel, (bool)(e.NewValue), null);
        }
    }
    

    And in your xaml :

    <DataGrid>
        <DataGrid.ItemsPanel>
            <ItemsPanelTemplate>
                <VirtualizingStackPanel IsItemsHost="True" local:VirtualizingStackPanelBehaviors.IsPixelBasedScrolling="True" />
            </ItemsPanelTemplate>
        </DataGrid.ItemsPanel>
    </DataGrid>
    
    0 讨论(0)
提交回复
热议问题