【问题标题】:How to get text from TextBox inside ListViewItem's DataTemplate如何从 ListViewItem 的 DataTemplate 中的 TextBox 获取文本
【发布时间】:2015-01-15 15:28:12
【问题描述】:

我不知道如何在单击按钮后从“firstBox”和“secondBox”获取文本。

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

我只得到对象

private void Button_Click_1(object sender, RoutedEventArgs e)
{
   var myobject = (sender as Button).DataContext;            
}

【问题讨论】:

标签: c# xaml listview windows-phone-8.1


【解决方案1】:

有很多方法可以做到这一点,例如,您可以遍历单击按钮父级的 VisualTree 并使用您想要的名称检索 TextBox。在这种情况下,我将利用yasen in this answer 编写的扩展方法。

然后它可以看起来像这样:

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

记得在 static 类的某处放置扩展方法:

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

【讨论】:

    【解决方案2】:

    这是获取文本的方法..

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

    注意: firstBoxsecondBox 必须是类成员才能在不同的类方法中使用它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-18
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      • 1970-01-01
      • 2017-10-04
      • 2021-03-14
      • 2013-05-13
      相关资源
      最近更新 更多