1

我创建了一个带有文本块和图像的 LongListSelector,然后如何点击图像以在列表中显示所选项目名称,然后点击项目名称以显示消息框?下面是我绑定名称和图像的代码:

<phone:PhoneApplicationPage.Resources>
        <DataTemplate x:Key="TileDataTemplate">
            <Grid Background="{StaticResource TransparentBrush}"
                  Margin="0, 0, 0, 12" Height="60">
                <TextBlock Text="{Binding Name}" Margin="60, 10, 0, 0" FontSize="24" Height="60">
                </TextBlock>
                <Image x:Name="GetName" Tap="GetName_Tap" Grid.Column="0" Source="/Assets/AppBar/Delete.png" Height="40" Width="40"
                                Margin="0, 6, 0, 5" HorizontalAlignment="Right" VerticalAlignment="Top" />
            </Grid>
        </DataTemplate>
</phone:PhoneApplicationPage.Resources>

    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <phone:LongListSelector
                    SelectionChanged="MainLongListSelector_SelectionChanged"
                    Margin="10,6,0,0"
                    ItemsSource="{Binding Staff.Items}"
                    LayoutMode="Grid"
                    GridCellSize="400,80"
                    ItemTemplate="{StaticResource TileDataTemplate}"
                    />
    </Grid>

代码背后:

private void MainLongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
   MessageBox.Show("Hi");
}

private void GetName_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
   LongListSelector selector = sender as LongListSelector;
   StaffData data = selector.SelectedItem as StaffData;
   MessageBox.Show(data.Name);
}

当我点击文本块时,消息“嗨”显示成功。但是如果我点击图像,我会得到空值。我该如何解决?谢谢

4

1 回答 1

6

sender不是 LongListSelector 而是用户点击的图像,因此出现空错误。

基本上,您只想检索用户点击的项目?在这种情况下,使用DataContext被点击控件的属性来检索它:

private void GetName_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
   var element = (FrameworkElement)sender;
   StaffData data = (StaffData)element.DataContext;
   MessageBox.Show(data.Name);
}

(FrameworkElement 是每个 UI 控件的基本类型。使用它,您不必担心它是图像、文本块……)

于 2013-08-21T09:01:08.313 回答