locked
Can't access textbox in datacontext in hubsection from code behind

    Question

  •  am making a windows phone 8.1 application, i am using hub section template and in that i have a textbox, i want to access its value on an event. I can't find a way to do so, i am not using any binding.

     Here is XAML

    <HubSection x:Uid="HubSection4" Header="SEARCH PACKAGE" DataContext="{Binding Groups[2]}" HeaderTemplate="{ThemeResource HubSectionHeaderTemplate}">
    
                    <DataTemplate>
    
                        <TextBox x:Name="searchBox" IsSpellCheckEnabled="True"  KeyDown="AnyKeyDown"/>
                    </DataTemplate>     
      
    </HubSection>

    Here is code:

     
     private async void AnyKeyDown(object sender, KeyRoutedEventArgs e)
            {
    
                if (e.Key == Windows.System.VirtualKey.Enter)
                {
                    //call the magic function
                    var messageDialog = new MessageDialog(searchBox.data);
                    // Show the message dialog
                    await messageDialog.ShowAsync();
    
                }
               
    
    
              }


    Sunday, October 19, 2014 11:33 AM

Answers

  • If you want to access the TextBox in the AnyKeyDown event handler you could just cast the sender object:

    private async void AnyKeyDown(object sender, KeyRoutedEventArgs e)
            {
                TextBox searchBox = sender as TextBox;
                if (e.Key == Windows.System.VirtualKey.Enter)
                {
                    //call the magic function
                    var messageDialog = new MessageDialog(searchBox.Text);
                    // Show the message dialog
                    await messageDialog.ShowAsync();
    
                }
            }
    
    Please remember to mark helpful posts as answer and/or helpful.
    Sunday, October 19, 2014 11:51 AM

All replies

  • If you want to access the TextBox in the AnyKeyDown event handler you could just cast the sender object:

    private async void AnyKeyDown(object sender, KeyRoutedEventArgs e)
            {
                TextBox searchBox = sender as TextBox;
                if (e.Key == Windows.System.VirtualKey.Enter)
                {
                    //call the magic function
                    var messageDialog = new MessageDialog(searchBox.Text);
                    // Show the message dialog
                    await messageDialog.ShowAsync();
    
                }
            }
    
    Please remember to mark helpful posts as answer and/or helpful.
    Sunday, October 19, 2014 11:51 AM
  • Thanks, it works now :)
    Sunday, October 19, 2014 12:08 PM