ListBox items return string, when DataTemplate is Button
Solution 1:
You need FrameworkTemplate.FindName Method (String, FrameworkElement)
for this purpose:
private childItem FindVisualChild<childItem>(DependencyObject obj)
where childItem : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is childItem)
return (childItem)child;
else
{
childItem childOfChild = FindVisualChild<childItem>(child);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}
Then:
for (int i = 0; i < Game_ScrollViewer_online.Items.Count; i++)
{
ListBoxItem GameListBoxItem = (ListBoxItem)(Game_ScrollViewer_online.ItemContainerGenerator.ContainerFromIndex(i));
ContentPresenter contentPresenter = FindVisualChild<ContentPresenter>(GameListBoxItem);
DataTemplate myDataTemplate = contentPresenter.ContentTemplate;
Button tempBut = (Button) myDataTemplate.FindName("Current_game_button", contentPresenter);
//Do stuff with button
}
To solve missing FindName
use FindDescendant
like this:
public T FindDescendant<T>(DependencyObject obj) where T : DependencyObject
{
if (obj is T)
return obj as T;
int childrenCount = VisualTreeHelper.GetChildrenCount(obj);
if (childrenCount < 1)
return null;
for (int i = 0; i < childrenCount; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child is T)
return child as T;
}
for (int i = 0; i < childrenCount; i++)
{
DependencyObject child = FindDescendant<T>(VisualTreeHelper.GetChild(obj, i));
if (child != null && child is T)
return child as T;
}
return null;
}