WPF列表框控件

时间:2014-12-20 09:33:08

标签: c# wpf listbox

我是WPF的新手。我想获取TextBlock控件的文本,该文本对应于在其UserList_SelectionChanged事件中选择的特定Listitem。

 <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>

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:2)

请仔细阅读以下示例

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>

在代码背后

 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);
    }       
}

答案 1 :(得分:1)

我看不出将ListBox放在ListView中的重点,反思一下。这里有TextBlock

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