ListBox items return a string when a DataTemplate is a Button

I am building a WP 8.1 Silverlight application.

I have an ObservableCollection of row names that is set to ItemsSource for a ListBox . What are the names of the buttons in the ListBox . Then I want to extract the buttons from the ListBox , but the return value is of type string .

Xaml code:

 <ListBox x:Name="Game_ScrollViewer_online" Margin="41,104,128,6" SelectedValuePath="Current_game_button"> <ListBox.ItemTemplate> <DataTemplate> <Button x:Name="Current_game_button" Content="{Binding}" HorizontalAlignment="Center" Height="80" Margin="-14,6,-15,0" VerticalAlignment="Top" Width="210" Template="{StaticResource Button_CurrentLayout1}" RenderTransformOrigin="0.5,0.5" Foreground="#FFCBECCB" FontFamily="Times New Roman" Click="LoadGame_online" FontSize="16"> </Button> </DataTemplate> </ListBox.ItemTemplate> </ListBox> 

Then I want to extract the button element:

 for (int i = 0; i < Game_ScrollViewer_online.Items.Count; i++) { var tempType = Game_ScrollViewer_online.Items[i].GetType(); Button tempBut = (Game_ScrollViewer_online.Items[i] as Button); //Do stuff with button } 

But as said, the return type is a string.

Why is this not a button? And is there a way to access the button?

+4
source share
1 answer

For this you need FrameworkTemplate.FindName Method (String, FrameworkElement) :

 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 the problem with the missing FindName , use FindDescendant as follows:

 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; } 
+1
source

Source: https://habr.com/ru/post/1245296/


All Articles