从作为子项的datatemplete访问scrollviewer作为父级 [英] Access scrollviewer as a parent from datatemplete as child
问题描述
如果MessageListItemControl ex中有新项目,我需要附加属性触发器自动滚动到底部:
I need an attached property trigger auto scroll to bottom if there is a new item in MessageListItemControl ex:
<Grid VerticalAlignment="Bottom" d:DataContext="{x:Static core:MessageListDesignModel.Instance}">
<ScrollViewer
local:ScrollToBottomOnLoadProperty.Value="True"
<ItemsControl ItemsSource="{Binding Items}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:MessageListItemControl
From There controll scrollviewer
local:SlideInOnLoadProperty.Value="{Binding NewItem}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
推荐答案
您好&NBSP; &NBSP; Shereif Awad,
>>从datatemplete作为子级访问scrollviewer作为父级
>>如果MessageListItemControl ex中有新项目,我需要一个附加属性触发器自动滚动到底部:
$
当你在MessageListItemControl中添加一个新项,它将触发一个事件,该事件将找到ScrollViewer和Scroll To End。
所以,我建议你尝试以下建议。
1:为ItemsControl ItemsSource定义一个ObservableCollection,并将一个监听器注册到集合的CollectionChanged-event:
Hi Shereif Awad,
>>Access scrollviewer as a parent from datatemplete as child
>>I need an attached property trigger auto scroll to bottom if there is a new item in MessageListItemControl ex:
When you add a new item in MessageListItemControl, it will trigger an event, the event will find the ScrollViewer and Scroll To End.
So, I suggest you try the following suggestion.
1: Define a ObservableCollection for your ItemsControl ItemsSource and Register a listener to collection's CollectionChanged-event:
Collectionsitems.CollectionChanged += (s, args) => ScrollToBottom();
2:您可以使用VisualTreeHelper查找控件。下面是一个方法,它使用VisualTreeHelper查找指定类型的父控件(ScrollViewer)。
public static class UIHelper
{
public static T FindVisualParent<T>(DependencyObject child)
where T : DependencyObject
{
// get parent item
DependencyObject parentObject = VisualTreeHelper.GetParent(child);
// we’ve reached the end of the tree
if (parentObject == null) return null;
// check if the parent matches the type we’re looking for
T parent = parentObject as T;
if (parent != null)
{
return parent;
}
else
{
// use recursion to proceed with next level
return FindVisualParent<T>(parentObject);
}
}
}
3:在ScrollToBottom方法中,找到ScrollIntoView并滚动到结尾。
3: In the ScrollToBottom-method, find the ScrollIntoView and scroll to the end.
private void ScrollToBottom()
{
ScrollViewer scrollviewer = UIHelper.FindVisualParent<ScrollViewer>(tetecontrol);
if (scrollviewer!=null)
{
scrollviewer.ScrollToEnd();
}
}
$
这篇关于从作为子项的datatemplete访问scrollviewer作为父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!