How to get text from TextBox inside ListViewItem DataTemplate

I do not know how to get text from "firstBox" and "secondBox" after clicking a button.

<ListView.ItemTemplate>
    <DataTemplate>
      <Grid>
       <!-- some code -->
       <TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding Data}" VerticalAlignment="Top" Height="18" Width="100" FontSize="13.333" Margin="162,9,0,0"/>
       <TextBlock HorizontalAlignment="Left" Margin="0,35,0,0" TextWrapping="Wrap" Text="{Binding D_gospodarzy}" FontSize="14.667" VerticalAlignment="Top" Height="59" Width="100"/>
       <TextBlock HorizontalAlignment="Center" Margin="268,35,7,0" TextWrapping="Wrap" Text="{Binding D_gosci}" FontSize="14.667" VerticalAlignment="Top" Width="100" Height="59"/>
       <TextBox x:Name="firstBox" ... />
       <Button Content="Click" " Click="Button_Click_1"/>
       <TextBox x:Name="secondBox" ... />
     </Grid>
   </DataTemplate>
</ListView.ItemTemplate>

I only get the object

private void Button_Click_1(object sender, RoutedEventArgs e)
{
   var myobject = (sender as Button).DataContext;            
}
+4
source share
2 answers

There are a bunch of ways to do this, for example, you can cross VisualTree by clicking on the button of the parent element and extract the TextBox with the desired name. In this case, I would use the extension method written by yasen in this answer .

Then it might look like this:

private void Button_Click_1(object sender, RoutedEventArgs e)
{
    var parent = (sender as Button).Parent;
    TextBox firstOne = parent.GetChildrenOfType<TextBox>().First(x => x.Name == "firstBox");
    Debug.WriteLine(firstOne.Text);
}

Remember to put the extension method somewhere in the static class:

public static class Extensions
{
    public static IEnumerable<T> GetChildrenOfType<T>(this DependencyObject start) where T : class
    {
          // rest of the code
+1
source

Here's how to get the text.

 String text1 = firstBox.Text;
 String text2 = secondBox.Text;

note: firstBox secondBox , .

0

All Articles