[英]How to access the button inside ItemsControl->ItemTemplate->DataTemplate->StackPanel? wpf c#
如何从xaml中的此结构获取代码背后的按钮?
<ItemsControl BorderBrush="Black" BorderThickness="2" Name="cat1" ItemsSource="{Binding Questions[0]}" Margin="65,0,0,165">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Name="sp1">
<Button Width="60" Content="{Binding Points}" Height="30" Tag="{Binding Id}" CommandParameter="{Binding RelativeSource={RelativeSource Self}}" Command="{Binding ElementName=cat1, Path=DataContext.QuestionButtonClick}">
</Button>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
我试图获得名称为stackpanel的东西
试图从许多foreach
获取它
您可以使用VisualTreeHelper
在窗口的当前可视树上获取元素。
为了方便起见,可以使用以下扩展方法,该方法可以在可视树上递归查找具有指定类型或条件的所有子元素。
public static class DependencyObjectExtensions
{
public static IEnumerable<T> GetChildren<T>(this DependencyObject p_element, Func<T, bool> p_func = null) where T : UIElement
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(p_element); i++)
{
UIElement child = VisualTreeHelper.GetChild(p_element, i) as FrameworkElement;
if (child == null)
{
continue;
}
if (child is T)
{
var t = (T)child;
if (p_func != null && !p_func(t))
{
continue;
}
yield return t;
}
else
{
foreach (var c in child.GetChildren(p_func))
{
yield return c;
}
}
}
}
}
然后,在加载窗口时,您将获得如下所有按钮:
var buttons = this.cat1.GetChildren<Button>().ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.