我正在从我的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
。
什么叫什么?或者我可以访问的地方。
答案 0 :(得分:-1)
通过添加新模板找到它:
<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}"
在我的虚拟机中将此设置为false会导致视图在渲染后崩溃。
原因是ListBox/ListView
在显示之前不会呈现他们的Template
(效率更高)。