4

I don't know how to get text from "firstBox" and "secondBox" after button click.

<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 get only the object

private void Button_Click_1(object sender, RoutedEventArgs e)
{
   var myobject = (sender as Button).DataContext;            
}
Romasz
  • 29,662
  • 13
  • 79
  • 154
jukiduki
  • 39
  • 1
  • 4
  • See this question and the answer from Jerry http://stackoverflow.com/questions/16375375/how-do-i-access-a-control-inside-a-xaml-datatemplate – Barnstokkr Jan 15 '15 at 07:23

2 Answers2

1

There are cuple of ways to do it, for example you can traverse the VisualTree of clicked button's parent and retrive TextBox with the name you want. In this case, I would take advantage of an extension method written by yasen in this answer.

Then it can look for example 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 an extension method somewhere in a static class:

public static class Extensions
{
    public static IEnumerable<T> GetChildrenOfType<T>(this DependencyObject start) where T : class
    {
          // rest of the code
Community
  • 1
  • 1
Romasz
  • 29,662
  • 13
  • 79
  • 154
0

Here's how to get the text..

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

note: firstBox and secondBox must be class members to use them in different class methods.

Dyrandz Famador
  • 4,499
  • 5
  • 25
  • 40