2012-11-14 17 views
6

我有一個DataGrid完整的筆記,可能會有一個筆記會比DataGrid的高度更高。發生這種情況時,如果嘗試向下滾動以閱讀註釋的下半部分,則DataGrid會立即跳到下一行。當行高於視口時,如何讓DataGrid平滑滾動?

這不僅會阻止用戶查看完整音符,還會導致滾動感覺不連貫,因爲它似乎在跳轉。

有沒有辦法讓WPF在不禁用默認DataGrid虛擬化的情況下順利滾動瀏覽長記錄?

+0

你們能不能換的音符在'ScrollViewer'其'MaxHeight'設置爲DataGrid的高度? – McGarnagle

+1

@dbaseman我希望標題始終可見,並且這將禁用DataGrid的虛擬化,因爲它會呈現所有項目 – Rachel

+0

您是否嘗試過爲dataGrid的ScrollViewer設置'CanContentScroll'爲'False'? –

回答

19

我相信你正在尋找可以在DataGrid上設置的VirtualizingPanel.ScrollUnit附屬屬性。

如果您將其值設置爲Pixel而不是默認Item,則應該按照您的要求進行操作。

+3

這應該做的伎倆如果@Rachel使用.NET 4.5 – Sisyphe

+0

不幸的是我使用.Net 4.0,但對於我升級我使用的.Net框架的版本來說,還不算太晚,所以如果沒有找到其他簡單的解決方案,我會考慮這樣做。謝謝。 – Rachel

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>