Reputation: 111
How can I get button in code behind from this structure in 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>
I tried to get stackpanel with name
tried to get it from many foreach
es
Upvotes: 0
Views: 895
Reputation: 1076
You can use VisualTreeHelper
to get the element on the current visual tree of your window.
For convenience, you can use the following extension method that can finds all children elements with the specified type or condition recursively on the visual tree.
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;
}
}
}
}
}
Then when the window is loaded, you can get all the buttons like this:
var buttons = this.cat1.GetChildren<Button>().ToList();
Upvotes: 1