我有一个装满笔记的 DataGrid,并且一个笔记可能会比 DataGrid 的高度高。发生这种情况时,如果您尝试向下滚动以阅读注释的下半部分,DataGrid 会立即跳到下一行。
这不仅会阻止用户查看完整的笔记,而且还会导致滚动感觉不连贯,因为它看起来会跳来跳去。
有没有办法告诉 WPF 在不禁用默认 DataGrid 虚拟化的情况下平滑滚动过长音符?
我相信您正在寻找VirtualizingPanel.ScrollUnit可以在 DataGrid 上设置的附加属性。
如果将其值设置为Pixel而不是 default Item,它应该做你想做的事。
如果您不想升级到 .NET 4.5,您仍然可以IsPixelBased在底层 VirtualizingStackPanel 上设置该属性。但是,此属性在 .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>