ajita srivastava
ajita srivastava

Reputation: 45

WPF Listbox control

I am new to WPF.I want to get the text of the TextBlock Control corresponding to the particular Listitem which is selected on its UserList_SelectionChanged event.

 <ListView Height="188" Canvas.Left="11" Canvas.Top="167" Width="252">

            <ListBox Name="UserList" Width="224" BorderThickness="0" SelectionChanged="UserList_SelectionChanged_1">
                    <ListBoxItem>
                        <StackPanel Orientation="Horizontal">
                            <Image Source="Status-user-online-icon.png" Height="19" Width="18" />
                            <TextBlock FontSize="14" FontStretch="Expanded" Width="98">User1</TextBlock>
                            <Line Stroke="red" X1="0" Y1="25" X2="{Binding ElementName=root, Path=Width}" Y2="25" Opacity="0.22" />
                        </StackPanel>

                    </ListBoxItem>
                    <ListBoxItem>
                        <StackPanel Orientation="Horizontal">
                            <Image Source="Status-user-online-icon.png" Height="19" Width="18" />
                            <TextBlock FontSize="14" FontStretch="Expanded" Width="98">User2</TextBlock>
                            <Line Stroke="red" X1="0" Y1="25" X2="{Binding ElementName=root, Path=Width}" Y2="25" />
                        </StackPanel>

                    </ListBoxItem>
              </ListBox>

  </ListView>

Any help would be appreciated.

Upvotes: 0

Views: 93

Answers (2)

Gun
Gun

Reputation: 1411

Please go through the below example

Xaml -

<Grid>
    <ListView Name="lstView" Margin="10" SelectionChanged="lstView_SelectionChanged">
    <ListViewItem>
        <StackPanel Orientation="Horizontal"> 
            <TextBlock>One</TextBlock>
        </StackPanel>
    </ListViewItem>
    <ListViewItem>
        <StackPanel Orientation="Horizontal">
            <TextBlock>Two</TextBlock>
        </StackPanel>
    </ListViewItem>
    <ListViewItem>
        <StackPanel Orientation="Horizontal">
            <TextBlock>Three</TextBlock>
        </StackPanel>
    </ListViewItem>
    </ListView>
</Grid>

In code behind

 private void lstView_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
    object selectedEntry = lstView.SelectedItem;
    ListBoxItem lbi = (ListBoxIte)lstView.SelectedItem;
    var stackPanel = lbi.Content as StackPanel;

    foreach (var child in stackPanel.Children)
    {
        MessageBox.Show((child as TextBlock).Text);
    }       
}

Upvotes: 2

Maximus
Maximus

Reputation: 3448

I cannot see the point of puting ListBox inside ListView, reflect on that. Here you have your TextBlock

((StackPanel)((ListBoxItem)UserList.SelectedItem).Content).Children.OfType<TextBlock>().FirstOrDefault();

Upvotes: 1

Related Questions