检测在Listbox DataTemplate上选择的内容

时间:2014-01-21 23:20:29

标签: c# .net xaml windows-phone-8 windows-phone

我有一个Listbox,它绑定到一个包含两个元素的对象列表:一个字符串和一个图像

我想检测用户是否点按图片或文本块

这就是我的尝试:

这是我的xaml:

<ListBox x:name = "TheList"  ItemSource ="{Binding List}" SelectionChanged="SelectionChanged_1">
    <DataTemplate>
        <TextBlock Text = "{Binding Name}" />
        <Image ImageSource = "{Binding Picture}" />
        <StackPanel>
        <\StackPanel>
    <\DataTemplate>
</ListBox>

这是我背后的代码:

private void SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
    if (TheList.SelectedItem != null)
    {
        if(e.OriginalSource == sender as  TextBox ){
             MessageBox.Show("Text");

        }  else if(e.OriginalSource  == sender as Image ){

            MessageBox.Show("Image");

        }
    }
}

但是,如果我点击MessageBox显示“Text”

的图像,它就不起作用

如何检测图像或文本块是否已被点击?

3 个答案:

答案 0 :(得分:1)

你可以尝试:

<ListBox x:name = "TheList"  ItemSource ="{Binding List}" SelectionChanged="SelectionChanged_1">
<DataTemplate>
    <TextBlock Click=hTClick" Text = "{Binding Name}" />
    <Image Click="hIClick" ImageSource = "{Binding Picture}" />
    <StackPanel>
    <\StackPanel>
<\DataTemplate>

在代码背后:

private void hTClick(object sender, SelectionChangedEventArgs e)
{
    MessageBox.Show("text");
}
private void hIClick(object sender, SelectionChangedEventArgs e)
{
    MessageBox.Show("image");
}

这会告诉你你想要什么。

答案 1 :(得分:1)

您无法在ListBox控件的SelectionChanged事件上实现。但你可以这样做

<ListBox x:name = "TheList"  ItemSource ="{Binding List}" SelectionChanged="SelectionChanged_1">
   <DataTemplate>
     <TextBlock Text = "{Binding Name}" Tap="txtBlock_Tap" />
      <Image ImageSource = "{Binding Picture}" Tap="img_Tap"/>
      <StackPanel>
       <\StackPanel>
    <\DataTemplate>
</ListBox>

 private void txtBlock_Tap(object sender, System.Windows.Input.GestureEventArgs e)
    {
      MessageBox.Show("TextBlock click");
      var item = TheList.SelectedItem as your Type;
     }

 private void img_Tap(object sender, System.Windows.Input.GestureEventArgs e)
     {
       MessageBox.Show("Image click");
       var item = TheList.SelectedItem as your Type;
     }

答案 2 :(得分:-1)

我终于找到了答案:

我不得不添加这一行:

var myTappedobject = (Sender as FrameworkElement).DataContext as MyObject