从C#(XAML)获取datatemplate内的textBlock文本

时间:2014-08-12 10:07:57

标签: c# wpf xaml windows-phone-8

我想对textblock tap事件进行一些编码,我需要它的文本值 我的xaml就像下面的

    <ListBox x:Name="listBox1">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Height="auto" >
                    <TextBlock  Name="myTextBlock"  Text="{Binding Busnumber}"  Tap="buss_Tap"  />                     
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>

然后在文本块点击事件上,我想点击点击文本值

private void buss_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{        
    //i want to achieve this 
    // string aa= myTextBlock.text;
    //but this is not working so what to do here to achieve the same?
}

2 个答案:

答案 0 :(得分:1)

您将获得 TextBlock in sender parameter 。将它转换为Textblock并从那里获取文本:

string text = ((TextBlock)sender).Text;

答案 1 :(得分:1)

试试这个:

private void buss_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
    TextBlock txt = (TextBlock)sender;
    MessageBox.Show(txt.Text);
}
相关问题