如何滚动到的ScrollViewer的底部XAML和绑定自动? [英] How to scroll to the bottom of a ScrollViewer automatically with Xaml and binding?
问题描述
我有一个的TextBlock
,其内容被绑定到视图模型的字符串属性。这的TextBlock
被缠的ScrollViewer
。
I've got a TextBlock
whose content is binded to a string property of the ViewModel. This TextBlock
is wrapped around a ScrollViewer
.
我想要做的就是每一个日志改变时,的ScrollViewer
将滚动至底部。理想我想是这样的:
What I want to do is every time the logs change, the ScrollViewer
will scroll to the bottom. Ideally I want something like this:
<ScrollViewer ScrollViewer.HorizontalScrollBarVisibility="Auto"
ScrollPosition="{Binding Path=ScrollPosition}">
<TextBlock Text="{Binding Path=Logs}"/>
</ScrollViewer>
我不想后面使用code!我在寻找解决的办法应该使用的仅结合和/或XAML中。
I don't want to use Code Behind! The solution I'm looking for should be using only binding and/or Xaml.
推荐答案
您可以创建一个附加属性或行为来达到你想要什么,而无需使用code后面。无论哪种方式,你仍然需要编写一些code。
You can either create an attached property or a behavior to achieve what you want without using code behind. Either way you will still need to write some code.
下面是使用附加属性的例子。
Here is an example of using attached property.
附加属性
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();
}
}
}
XAML绑定
<ScrollViewer local:Helper.AutoScroll="{Binding IsLogsChangedPropertyInViewModel}" .../>
您将需要创建一个布尔属性 IsLogsChangedPropertyInViewModel
键,当字符串属性更改其设置为true。
You will need to create a boolean property IsLogsChangedPropertyInViewModel
and set it to true when the string property is changed.
希望这有助于! :)
这篇关于如何滚动到的ScrollViewer的底部XAML和绑定自动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!