如何获取信息表单ListBox中的Header



当我点击listBox项目时,我会在"selectionChanged"事件中得到一个子项目。我也需要获得头衔。我怎样才能做到这一点?

public class Data
{
    public string Title { get; set; }
    public List<SubItem> SubItems { get; set; }
    public Data()
    {
        SubItems = new List<SubItem>();   
    }    
}
<phone:LongListSelector ItemsSource="{Binding DataCollection}" Grid.Row="0">
    <phone:LongListSelector.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Title}" Padding="5" />
                    <TextBlock Text="{Binding ImageSource}" Padding="5"/>
                </StackPanel>
                <ListBox ItemsSource="{Binding SubItems}" SelectionChanged="ListBox_SelectionChanged">
                    <ListBox.ItemsPanel>
                        <ItemsPanelTemplate>
                            <StackPanel Orientation="Vertical"/>
                        </ItemsPanelTemplate>
                    </ListBox.ItemsPanel>
                    <ListBox.ItemTemplate>
                        <DataTemplate>                                   
                            <TextBlock Text="{Binding SubItemTitle}" Margin="0,0,12,0" Padding="10" />
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </StackPanel>
        </DataTemplate>
    </phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>

SelectionChanged事件中,可以通过强制转换sender参数来检索ListBox。从那里,您可以通过投射datacontext:来检索您的Data对象

private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var listBox = (ListBox)sender;
    var data = (Data)listBox.DataContext;
    System.Diagnostics.Debug.WriteLine(data.Title);
}

在您的selectionChanged事件下,尝试以下操作:

string text = (listBox.SelectedItem as ListBoxItem).Content.ToString(); //listBox is the name of the Listbox

一个更好的参考可以是:

正在从绑定的ListBox 中获取所选项目字符串

希望它能有所帮助!

最新更新