Reputation: 175
I have a listbox, I have set a stackpanel and textblock in that. I want the last textblock's text because I have a set a value on last textbox text by using a converter.
The code posted below is tried by me and is not working
private void listname_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string textt = (((sender as ListBox) as StackPanel).Children[1] as TextBlock).Text;
//StackPanel sPanel = (sender as StackPanel) as StackPanel;
//var tbxCollection = from tbx in sPanel.Children.OfType<TextBlock>()
// where tbx.Name == "bl"
// select tbx;
Upvotes: 2
Views: 597
Reputation: 29792
If you want to search your ContentControl (ListBoxItem) for Controls, then you can use VisualTreeHelper class for this purpose.
The code below will help you to search for a specific Control(s) in DependencyObject - parent:
private static void SearchForControls<T>(DependencyObject parent, ref List<T> controlList) where T : DependencyObject
{
int numberOfChildreen = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numberOfChildreen; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is T) controlList.Add((T)child);
else SearchForControls<T>(child, ref controlList);
}
}
With this pice of code you can manage to complete your task like this:
private void myList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBoxItem item = (sender as ListBox).ItemContainerGenerator.ContainerFromIndex((sender as ListBox).SelectedIndex) as ListBoxItem;
List<StackPanel> controlList = new List<StackPanel>();
SearchForControls<StackPanel>(item, ref controlList);
string text = (controlList[0].Children[1] as TextBlock).Text;
}
In above code, in controlList
you will get all StackPanels
from you SelectedItem
(accessed by SelectedIndex
). For this example I assume that you have one StackPanel
- hopefuly this will help you. Try to debug it and you will see how it works.
Upvotes: 2
Reputation: 3331
it would be better and easier to subscribe to textblocks Tap event instead
<DataTemplate>
<Textblock name="myTxtBlock" Tap="myTxtBlock_Tap"/>
</DataTemplate>
in code:
private void myTxtBlock_Tap(object sender, GestureEventArgs e)
{
string text=(Sender as Textblock).Text;
}
Upvotes: 0