How to get text from TextBox inside ListViewItem's DataTemplate

笑着哭i 提交于 2019-12-07 10:12:55

问题


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

回答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



回答2:


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.



来源:https://stackoverflow.com/questions/27956830/how-to-get-text-from-textbox-inside-listviewitems-datatemplate

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