如何在 WPF 中的 TabItem 中获取 ScrollViewer
How do I get a ScrollViewer inside TabItem In WPF
我需要在当前 TabItem 中找到一个 ScrollViewer,然后在该 ScrollViewer 中找到一个 WrapPanel
我试过这个:
TabItem ti = tabControl.SelectedItem as TabItem;
foreach (ScrollViewer sv in ti.Content)
{
foreach (WrapPanel wp in sv.Content) {}
}
还有这个
TabItem ti = tabControl.SelectedItem as TabItem;
foreach (ScrollViewer sv in ti.Children)
{
foreach (WrapPanel wp in sv.Children) {}
}
但是不起作用
如果您的标签项直接包含您的滚动查看器,您可以执行以下操作:
TabItem ti = tabControl.SelectedItem as TabItem;
ScrollViewer sv = ti?.Content as ScrollViewer;
WrapPanel wp = scrollViewer?.Content as WrapPanel;
访问 WrapPanel 的另一种方法是使用 returns 特定类型的 child/content 函数。例如
public T FindVisualChildOrContentByType<T>(DependencyObject parent)
where T : DependencyObject
{
if(parent == null)
{
return null;
}
if(parent.GetType() == typeof(T))
{
return parent as T;
}
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if(child.GetType() == typeof(T))
{
return child as T;
}
else
{
T result = FindVisualChildOrContentByType<T>(child);
if (result != null)
return result;
}
}
if(parent is ContentControl contentControl)
{
return this.FindVisualChildOrContentByType<T>(contentControl.Content as DependencyObject);
}
return null;
}
那你就可以
WrapPanel wp = this.FindVisualChildOrContentByType<WrapPanel>(tabItem);
如果这不起作用,请随时 post 您的 XAML 以便我可以重现您的确切场景。
我需要在当前 TabItem 中找到一个 ScrollViewer,然后在该 ScrollViewer 中找到一个 WrapPanel
我试过这个:
TabItem ti = tabControl.SelectedItem as TabItem;
foreach (ScrollViewer sv in ti.Content)
{
foreach (WrapPanel wp in sv.Content) {}
}
还有这个
TabItem ti = tabControl.SelectedItem as TabItem;
foreach (ScrollViewer sv in ti.Children)
{
foreach (WrapPanel wp in sv.Children) {}
}
但是不起作用
如果您的标签项直接包含您的滚动查看器,您可以执行以下操作:
TabItem ti = tabControl.SelectedItem as TabItem;
ScrollViewer sv = ti?.Content as ScrollViewer;
WrapPanel wp = scrollViewer?.Content as WrapPanel;
访问 WrapPanel 的另一种方法是使用 returns 特定类型的 child/content 函数。例如
public T FindVisualChildOrContentByType<T>(DependencyObject parent)
where T : DependencyObject
{
if(parent == null)
{
return null;
}
if(parent.GetType() == typeof(T))
{
return parent as T;
}
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if(child.GetType() == typeof(T))
{
return child as T;
}
else
{
T result = FindVisualChildOrContentByType<T>(child);
if (result != null)
return result;
}
}
if(parent is ContentControl contentControl)
{
return this.FindVisualChildOrContentByType<T>(contentControl.Content as DependencyObject);
}
return null;
}
那你就可以
WrapPanel wp = this.FindVisualChildOrContentByType<WrapPanel>(tabItem);
如果这不起作用,请随时 post 您的 XAML 以便我可以重现您的确切场景。