您的位置:首页 > 其它

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

2008-04-24 17:49 323 查看

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;
}
}
}
运行这个示例程序,可以看到如图所示的结果。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: