2013-02-19 60 views
2

TextBlock有什麼功能可以讓滾動到最後?滾動wpf文本塊結束

我已經看到了一些在背後的代碼做這方面的例子,

我想保持MVVM的原則,並沒有觸及背後的代碼,

我在XAML尋找一種方法來做到這一點。

有一個嗎?

回答

4

我假設你的TextBlock嵌套在ScrollViewer內。在這種情況下,你將不得不創建一個附加屬性。請參閱此相關的問題:

How to scroll to the bottom of a ScrollViewer automatically with Xaml and binding?

即創建一個附加屬性:

public static class Helper 
{ 
    public static bool GetAutoScroll(DependencyObject obj) 
    { 
     return (bool)obj.GetValue(AutoScrollProperty); 
    } 

    public static void SetAutoScroll(DependencyObject obj, bool value) 
    { 
     obj.SetValue(AutoScrollProperty, value); 
    } 

    public static readonly DependencyProperty AutoScrollProperty = 
     DependencyProperty.RegisterAttached("AutoScroll", typeof(bool), typeof(Helper), new PropertyMetadata(false, AutoScrollPropertyChanged)); 

    private static void AutoScrollPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 
     var scrollViewer = d as ScrollViewer; 

     if (scrollViewer != null && (bool)e.NewValue) 
     { 
      scrollViewer.ScrollToBottom(); 
     } 
    } 
} 

然後綁定如下:

<ScrollViewer local:Helper.AutoScroll="{Binding BooleanViewModelPropertyThatTriggersScroll}" .../> 
+0

有沒有辦法只XAML做到這一點?這是最簡單的方法..? – 2013-02-19 06:46:15

+1

@HodayaShalom不,這不是平臺的支持功能。你將需要編寫一些代碼! – ColinE 2013-02-19 06:48:03

+1

好!謝謝.. – 2013-02-19 06:49:13