【问题标题】:Detect what has been selected on a Listbox DataTemplate检测列表框数据模板上已选择的内容
【发布时间】:2014-01-21 23:20:29
【问题描述】:

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

我想检测用户是否点击了图像或文本块

这是我尝试过的:

这是我的 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 显示“文本”的图像,它不起作用

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

【问题讨论】:

  • sender 将成为ListBoxItem,我想。试试if (e.OriginalSource is TextBlock)
  • 不,它不工作,现在它既没有检测到文本块也没有检测到图像
  • 你是对的,抱歉 - 看起来原始来源被 SelectionChanged 事件吞噬了。您可能需要考虑在ImageTextBlock 上分别添加Tap 事件。

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


【解决方案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");
}

这会告诉你你想要什么。

【讨论】:

    【解决方案2】:

    您无法实现 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;
         }
    

    【讨论】:

      【解决方案3】:

      我终于找到答案了:

      我必须添加这一行:

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

      【讨论】:

        猜你喜欢
        • 2011-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-01
        • 2021-11-26
        相关资源
        最近更新 更多