如何在listbox hold事件中获取listboxitem的值?

时间:2015-01-03 00:11:40

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

xmal代码:

<ListBox x:Name="listbox2" Margin="0,0" SelectionChanged="listbox2_SelectionChanged" Hold="listbox2_Hold" >

                    <ListBox.ItemContainerStyle >
                        <Style TargetType="ListBoxItem">
                            <Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>
                        </Style>
                    </ListBox.ItemContainerStyle>
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <Border BorderThickness="0,0,0,1" BorderBrush="Gray">
                                <Grid Width="auto" HorizontalAlignment="Stretch" >
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="*"/>
                                        <RowDefinition Height="*"/>
                                    </Grid.RowDefinitions>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="150"/>
                                        <ColumnDefinition Width="*"/>
                                    </Grid.ColumnDefinitions>
                                    <TextBlock VerticalAlignment="Center" FontSize="40" Grid.Column="1"  Grid.Row="0"  Foreground="White" Text="{Binding NAME}"></TextBlock>
                                    <TextBlock VerticalAlignment="Center" FontSize="25" Grid.Column="1" Grid.Row="1" Foreground="Blue" Text="{Binding PHONE}"></TextBlock>
                                    <Image  Name="c1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="100" Height="100" Stretch="Fill" Margin="0" Source="{Binding IMGS}" Grid.RowSpan="2" Grid.Column="0" />

                                </Grid>
                            </Border>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>

绑定到列表框的类列表是   列表&lt; contactsclass&gt; contacts = new List&lt; contactsclass&gt;(); PHONE和NAME是contactclass变量的getter setter

如何在列表框的保留事件中获取此变量的值...我正在尝试以下代码

 private void listbox2_Hold(object sender, System.Windows.Input.GestureEventArgs e)
    {

         //contextmenucontact = (contactsclass)(sender as ListBox).DataContext;
           contextmenucontact = (contactsclass)listbox2.SelectedItem;


         MessageBox.Show(contextmenucontact.name);

      }

1 个答案:

答案 0 :(得分:0)

如果只是选中的项目只是使用ToString函数,请参阅:

        if (listBox1.SelectedItem != null)
        {
            string itemText = listBox1.SelectedItem.ToString();
            contextmenucontact = new contactsclass();
            contextmenucontact.name = itemText;
            MessageBox.Show(contextmenucontact.name);
        }