精通Silverlight——12.4.9 ListBox列表框控件

来源:互联网 发布:国际心理咨询师 知乎 编辑:程序博客网 时间:2024/05/18 12:02

Silverlight SDK中还提供了一个类似于ASP.NET中的列表框控件。ListBox控件的声明XAML代码如下所示。

<uicontrol:ListBox x:Name="listBox" Canvas.Top="30" Canvas.Left="80" />

ScrollViewer控件类似,必须在后置代码中为ListBox控件添加内容,后置代码如下所示。

using System;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Ink;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

namespace ListBoxDemo

{

    public partial class Page : Canvas

    {

        public void Page_Loaded(object o, EventArgs e)

        {

            // Required to initialize variables

            InitializeComponent();

            //ListBox添加项

            for (int i = 0; i < 15; i++)

            {

                listBox.Items.Add(ListItem(i));

            }

            listBox.UpdateItems();

        }

        static int colorCounter = 50;

        //ListItem方法创建并返回一个FrameworkElement对象

        private FrameworkElement ListItem(int i)

        {

            // 每个FrameworkElement将位于一个画布上。

            Canvas canvas = new Canvas();

            canvas.Width = 156;

            canvas.Height = 50;

            //添加一个矩形

            Rectangle rect = new Rectangle();

            Color color = Color.FromArgb(0xff, (byte)(colorCounter % 256),

                                               (byte)((colorCounter + 50) % 256),

                                               (byte)((colorCounter + 120) % 256));

            //rect.Fill = new SolidColorBrush(color);

            rect.Width = 150;

            rect.Height = 44;

            rect.SetValue(Canvas.TopProperty, 3);

            rect.SetValue(Canvas.LeftProperty, 3);

            colorCounter += 21;

            canvas.Children.Add(rect);

            //在矩形上面添加一个文本块

            TextBlock tb = new TextBlock();

            tb.Text = "Item" + i;

            tb.SetValue(Canvas.TopProperty, 15);

            tb.SetValue(Canvas.LeftProperty, 50);

            canvas.Children.Add(tb);

            return canvas;

        }

    }

}

运行这个示例程序,可以看到如图所示的结果。

原创粉丝点击