[英]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. 单击按钮后,我不知道如何从“ 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>
I get only the object 我只得到对象
private void Button_Click_1(object sender, RoutedEventArgs e)
{
var myobject = (sender as Button).DataContext;
}
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. 有很多方法可以做到这一点,例如,您可以遍历单击按钮的父级的VisualTree并使用所需的名称检索TextBox 。 In this case, I would take advantage of an extension method written by yasen in this answer .
在这种情况下,我将利用yasen在此答案中编写的扩展方法。
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
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. 注意:
firstBox
和secondBox
必须是类成员,才能在不同的类方法中使用它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.