Getting the values of TextBox from a data bound ListBox

这一生的挚爱 提交于 2019-12-04 20:57:19

Solved it !

private void AppointmentResultsData_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var listBoxItem = AppointmentResultsData.ItemContainerGenerator.ContainerFromIndex(AppointmentResultsData.SelectedIndex) as ListBoxItem;
        var txtBlk = FindVisualChildByType<TextBlock>(listBoxItem, "txtLocation");

        MessageBox.Show(txtBlk.Text);
    }




T FindVisualChildByType<T>(DependencyObject element, String name) where T : class
    {
        if (element is T && (element as FrameworkElement).Name == name)
            return element as T;
        int childcount = VisualTreeHelper.GetChildrenCount(element);
        for (int i = 0; i < childcount; i++)
        {
            T childElement = FindVisualChildByType<T>(VisualTreeHelper.GetChild(element, i), name);
            if (childElement != null)
                return childElement;
        }
        return null;
    } 

Suppose you have a list of class(MyClass) objects which you have databinded to listbox

Add a handler gesturelistener tap to the datatemplate

In the handler do this:

private void ItemClickedEventHandler(object sender, Microsoft.Phone.Controls.GestureEventArgs e)
        {                   
           MyClass clickedMyclass = (MyClass)((System.Windows.Controls.Grid)sender).DataContext;

        }

you have the object of the current selected item and you can access all the class variables. eg(StartTime etc.)

Well you are casting it to the wrong type, this should work :

private void AppointmentResultsData_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {  
      var listBoxItem = AppointmentResultsData.SelectedItem as ListBoxItem;
      TextBox nameBox = listBoxItem .FindName("nameYourTextBox") as TextBox;
      TextBlock nameBlock = dd.FindName("nameYourTextBlock") as TextBlock;
      MessageBox.Show(nameBlock.Text + " " + nameBox.Text);
     }

of course you need to add the Name to your TextBox and TextBlock

<TextBlock x:Name="nameYourTextBlock Text="{Binding Path=Account.Name}" Grid.Column="0" Grid.Row="1" FontSize="28"/>

Plus I don't see any TextBox in your XAML.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!