[英]Getting scrollviewer from Collapsed ListBox
我正在努力從已折疊的列表框中獲取ScrollViewer。 這將是可見的,我已經嘗試過:
-載入后事件:
documentListBox.Loaded += (sender, e) =>
{
var scroller = documentListBox.Template.FindName("Scroller", documentListBox);
var scroller1 = LogicalTreeHelper.GetParent(documentListBox);
var scroller2 = VisualTreeHelper.GetParent(documentListBox);
var scroller3 = Extensions.GetDescendantByType(documentListBox, typeof(ScrollViewer)) as ScrollViewer;
var scroller4 = documentListBox.Template.FindName("ScrollViewer", documentListBox) as ScrollViewer;
}
----------------Extensions.GetDescendantByType:----------------
public static Visual GetDescendantByType(Visual element, Type type)
{
if (element == null)
{
return null;
}
if (element.GetType() == type)
{
return element;
}
Visual foundElement = null;
if (element is FrameworkElement)
{
(element as FrameworkElement).ApplyTemplate();
}
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
{
Visual visual = VisualTreeHelper.GetChild(element, i) as Visual;
foundElement = GetDescendantByType(visual, type);
if (foundElement != null)
{
break;
}
}
return foundElement;
}
-IsVisibleChanged之后:
documentListBox.IsVisibleChanged+=VisibilityChanged
VisibilityChanged(){
var scroller = Extensions.GetDescendantByType(documentListBox, typeof(ScrollViewer)) as ScrollViewer;
var scroller1 = documentListBox.Template.FindName("ScrollViewer", documentListBox) as ScrollViewer;
var scroller2 = VisualTreeHelper.GetParent(documentListBox);
var scroller3 = LogicalTreeHelper.GetParent(documentListBox);
}
在兩種情況下,也都嘗試覆蓋ListBox並添加此屬性:
public ScrollViewer Scroller
{
get
{
return GetTemplateChild("ScrollViewer") as ScrollViewer;
}
}
所有這些要么給了我其他東西,要么為null
。 有什么想法嗎? 或者在我可以訪問它的地方。
通過添加新模板找到它:
<ListBox.Template>
<ControlTemplate>
<ScrollViewer x:Name="Scroller">
<VirtualizingStackPanel Orientation="Vertical" IsItemsHost="True"/>
</ScrollViewer>
</ControlTemplate>
</ListBox.Template>
然后在我的Codebehind中覆蓋OnRender:
protected override void OnRender(DrawingContext dc)
{
base.OnRender(dc);
var scrollviewer = (documentListView.Template.FindName("Scroller", documentListView)) as ScrollViewer;
還必須更改可見性設置:
Visibility="{Binding ViewIsVisible, Converter={Panels:BoolToVisibilityConverter}, FallbackValue=Visible}"
在渲染后,在我的VM中將此設置為false會使視圖折疊。
原因是ListBox/ListView
不會在可見之前渲染其Template
(更有效)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.