如何获取列表框ItemsPanel在code背后 [英] How to get ListBox ItemsPanel in code behind
本文介绍了如何获取列表框ItemsPanel在code背后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个ItemsPanel一个ListBox
I have a ListBox with an ItemsPanel
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<StackPanel x:Name="ThumbListStack" Orientation="Horizontal" />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
我想移动堆栈面板以及使用落后code一个TranslateTransform X轴。
I am wanting to move the Stack Panel along the X-axis using a TranslateTransform in code behind.
但问题是,我找不到堆栈面板。
Problem is, I can't find the Stack Panel.
ThumbListBox.FindName("ThumbListStack")
返回什么。 我想使用它:
Returns nothing. I want to use it in:
Storyboard.SetTarget(x, ThumbListBox.FindName("ThumbListStack"))
我如何得到栈面板这样我就可以使用它与TranslateTransform
How do I get the Stack Panel so I can then use it with the TranslateTransform
感谢
推荐答案
您可以使用加载
事件的的StackPanel
是在 ItemsPanelTemplate
You can use the Loaded
event for the StackPanel
that is in the ItemsPanelTemplate
<Grid>
<Grid.Resources>
<Style TargetType="ListBox">
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<StackPanel x:Name="ThumbListStack" Orientation="Horizontal"
Loaded="StackPanel_Loaded" />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
</Style>
</Grid.Resources>
<ListBox />
</Grid>
然后在后面的code 的
private StackPanel m_itemsPanelStackPanel;
private void StackPanel_Loaded(object sender, RoutedEventArgs e)
{
m_itemsPanelStackPanel = sender as StackPanel;
}
另一种方式是遍历可视化树,并找到的StackPanel
这将是产品presenter的第一个孩子
。
public void SomeMethod()
{
ItemsPresenter itemsPresenter = GetVisualChild<ItemsPresenter>(listBox);
StackPanel itemsPanelStackPanel = GetVisualChild<StackPanel>(itemsPresenter);
}
private static T GetVisualChild<T>(DependencyObject parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
{
child = GetVisualChild<T>(v);
}
if (child != null)
{
break;
}
}
return child;
}
这篇关于如何获取列表框ItemsPanel在code背后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文