【问题标题】:How can I get a DataGrid to scroll smoothly when the Row is taller than the Viewport?当 Row 比 Viewport 高时,如何让 DataGrid 平滑滚动?
【发布时间】:2012-11-14 17:05:33
【问题描述】:

我有一个装满注释的 DataGrid,并且一个注释可能会比 DataGrid 的高度高。发生这种情况时,如果您尝试向下滚动以阅读注释的下半部分,DataGrid 会立即跳到下一行。

这不仅会阻止用户查看完整的笔记,而且还会导致滚动感觉不连贯,因为它似乎会跳来跳去。

有没有办法告诉 WPF 在不禁用默认 DataGrid 虚拟化的情况下平滑滚动过长音符?

【问题讨论】:

  • 您不能将便笺包装在ScrollViewer 中,而MaxHeightMaxHeight 设置为DataGrid 的高度吗?
  • @dbaseman 我希望标题始终可见,这将禁用 DataGrid 的虚拟化,因为它会呈现所有项目
  • 您是否尝试将 dataGrid 的 ScrollViewer 的 CanContentScroll 设置为 False
  • @RV1987 我为什么要这样做?我想要滚动行为,但我希望它在大项目中平滑滚动,而不是一次向下滚动一个项目。设置 CanContentScroll 会将滚动设置为 false 并禁用虚拟化
  • 你看过这个链接吗:stackoverflow.com/questions/3062540/…

标签: wpf datagrid


【解决方案1】:

我相信您正在寻找可以在 DataGrid 上设置的 VirtualizingPanel.ScrollUnit 附加属性。

如果您将其值设置为Pixel 而不是默认的Item,它应该会按照您的意愿行事。

【讨论】:

  • 不幸的是,我正在使用 .Net 4.0,但是升级我正在使用的 .Net 框架的版本还为时不晚,所以如果没有找到其他简单的解决方案,我会考虑这样做。谢谢。
【解决方案2】:

如果您不想升级到 .NET 4.5,您仍然可以在底层 VirtualizingStackPanel 上设置 IsPixelBased 属性。但是,此属性在 .NET 4.0 中是内部的,因此您必须通过反射来实现。

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);
    }
}

在你的 xaml 中:

<DataGrid>
    <DataGrid.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel IsItemsHost="True" local:VirtualizingStackPanelBehaviors.IsPixelBasedScrolling="True" />
        </ItemsPanelTemplate>
    </DataGrid.ItemsPanel>
</DataGrid>

【讨论】:

    猜你喜欢
    • 2015-09-23
    • 1970-01-01
    • 2011-01-19
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多