WPF - ListBox显示任意内容

来源:互联网 发布:沪昆高铁贵州段 知乎 编辑:程序博客网 时间:2024/06/03 06:43

WFP是非常强大的。ListBox是一个很常用的控件,看了一下它的items属性,定义如下:

public ItemCollection Items { get; }

这是一个collection,我没有仔细研究ItemCollection类,我只看了一下ItemCollection的一个成员函数Add,定义如下:

public int Add(object newItem);

哈哈,它的参数是object类型,那么也就是说可以存放任何对象。

这么说来ListBox里面的items可以是任何对象,这样我们就可以在item里面显示任何我们想要的效果。

 

XAML静态显示ListBox

先来看看XAML里面如何显示一个listbox。随便写了个例子,如下:

        <ListBox Margin="15,12,0,0" Name="listBox1" Height="121" HorizontalAlignment="Left" VerticalAlignment="Top" Width="129">            <ListBoxItem Background="Blue">item1</ListBoxItem>            <ListBoxItem>                <StackPanel Orientation="Horizontal">                    <Ellipse Fill="Yellow" Height="50" Width="50"></Ellipse>                    <Label>abcd</Label>                </StackPanel>            </ListBoxItem>            <ListBoxItem>                <StackPanel Orientation="Vertical">                    <Rectangle Fill="Red" Height="50" Width="100"></Rectangle>                    <TextBox>hello</TextBox>                </StackPanel>            </ListBoxItem>        </ListBox>

放了3个item,注意每个item只能有一个child,如果我们把StackPanel去掉,那么就会报错。如:

error MC3089: The object 'ListBoxItem' already has a child and cannot add 'TextBox'. 'ListBoxItem' can accept only one child. Line 17 Position 30.

所以,当item里面需要显示多个控件的时候,就需要StackPanel或者其他类似的一个容器。


C#动态设置item

通常,listbox的内容是动态生成的,那么我们可以使用C#来设置内容,比如:

        private void Window_Loaded(object sender, RoutedEventArgs e)        {            TextBox text = new TextBox();            text.Text = "hello world";            Ellipse ellipse = new Ellipse();            ellipse.Height = 50;            ellipse.Width = 50;            ellipse.Fill = new SolidColorBrush(Color.FromRgb(255, 0, 0));                       StackPanel panel = new StackPanel();            panel.Orientation = Orientation.Horizontal;            panel.Children.Add(text);            panel.Children.Add(ellipse);            listBox2.Items.Add(panel);            Label label = new Label();            label.Content = "book";            listBox2.Items.Add(label);        }

增加几行代码来读取内容,如:

        private void listBox2_SelectionChanged(object sender, SelectionChangedEventArgs e)        {            int i = listBox2.SelectedIndex;            switch(i)            {                case 0:                    StackPanel panel = (StackPanel)listBox2.SelectedItem;                    TextBox text = (TextBox)panel.Children[0];                    MessageBox.Show(text.Text, "hint");                    break;                case 1:                    Label l = (Label)listBox2.SelectedItem;                    MessageBox.Show((string)l.Content, "hint");                    break;                default:                    break;            }        }


 

运行一下,左边的listbox是XAML设置内容的,右边的是动态生成的。



原创粉丝点击