如何访问我选择的项目?列表框

时间:2011-04-19 14:48:44

标签: xaml windows-phone-7 listbox

我的xaml页面上有ListBox,名为MainListBox。我可以获得被选中的索引,但是如何从所选项目中获取数据?

我的MainListBox_SelectionChanged:

private void MainListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        int noteID1 = MainListBox.SelectedIndex+1;

        if (MainListBox.SelectedIndex != null)
        {


            //I can get the index that get selected, 
            Debug.WriteLine(MainListBox.SelectedIndex);



        }

         MainListBox.SelectedIndex = -1;

    }

我的XAML:

<ListBox x:Name="MainListBox" Margin="6,0,0,0" ItemsSource="{Binding Items}" SelectionChanged="MainListBox_SelectionChanged" Height="578" VerticalAlignment="Bottom" Grid.ColumnSpan="3">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Margin="0,0,0,17" Width="432">
                        <TextBlock x:Name="ItemText" Text="{Binding noteName}" Margin="-2,-13,0,0" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
                        <TextBlock x:Name="DetailsText" Text="{Binding noteText}" Margin="10,-6,0,3" Style="{StaticResource PhoneTextSubtleStyle}"/>
                        <TextBlock x:Name="noteIdText" Text="{Binding noteID}" Margin="10,-6,0,3" Style="{StaticResource PhoneTextSubtleStyle}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

请有人指导我,谢谢。 :)

5 个答案:

答案 0 :(得分:6)

你试过MainListBox.SelectedItem吗?

var data = MainListBox.Selecteditem as [类绑定到列表框的类型];

答案 1 :(得分:1)

假设您绑定Items的{​​{1}}属性的ListBox对象是类ItemsSource的对象集合。然后,在选择更改后的回调中使用以下内容:

MyDataObject

答案 2 :(得分:1)

感谢大家快速回复。

最后我明白了。

 if (MainListBox.SelectedItem != null)
        {


            var data = MainListBox.SelectedItem as Notes;

            NavigationService.Navigate(new Uri("/DetailsPage.xaml?noteID=" + data.noteID, UriKind.Relative));


        }

答案 3 :(得分:0)

SelectedItem是Items中的实体。您可以直接转换为实体类型。

SelectedItem也必须位于WP7中的System.Windows.Control.ListBox中。这是文档: http://msdn.microsoft.com/en-us/library/system.windows.controls.listbox.aspx http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.selector.selecteditem.aspx

答案 4 :(得分:0)

private void MyList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    DataModel data = (sender as ListBox).SelectedItem as DataModel;
    // data.MyPropertyHere;
}
相关问题