jukiduki
jukiduki

Reputation: 39

How to get text from TextBox inside ListViewItem's DataTemplate

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;            
}

Upvotes: 4

Views: 2676

Answers (2)

Romasz
Romasz

Reputation: 29792

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

Upvotes: 1

Dyrandz Famador
Dyrandz Famador

Reputation: 4525

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.

Upvotes: 0

Related Questions