在写silverlight程序的某些时候难免要动态创建控件或修改控件事件,以下为示例代码:

Code
1
2 public partial class EventDemo : UserControl
3 {
4 private int newButtonPosition = 100;
5
6 public EventDemo()
7 {
8 InitializeComponent();
9 //Anthor按钮单击事件
10 Another.Click += new RoutedEventHandler(Another_Click);
11 }
12
13 //Anthor按钮单击后,执行方法
14 void Another_Click(object sender, RoutedEventArgs e)
15 {
16 //创建一个Button
17 Button b = new Button();
18 //显示内容
19 b.Content = "I live!";
20 //为新创建的控件新建Thickness对象,用来设置Button控件的位置
21 //原文中使用了Canvas.LeftProperty和Canvas.TopProperty
22 Thickness tn = new Thickness(10,this.newButtonPosition,0,0);
23 b.SetValue(Canvas.StyleProperty, tn);
24 //到顶部的距离递增
25 this.newButtonPosition += 30;
26 b.Width = 100;
27 b.Height = 20;
28 //给这个新建的按钮的Click事件添加一个处理方法
29 b.Click += new RoutedEventHandler(b_Click);
30 //添加到父控件,并显示
31 myCanvas.Children.Add(b);
32 }
33
34 //点击添加的控件触发
35 void b_Click(object sender, RoutedEventArgs e)
36 {
37 Button btn = sender as Button;
38 btn.Content = "Don't do that!";
39 btn.IsEnabled = false;
40 }
41 }
42
43


1
2 public partial class EventDemo : UserControl
3 {
4 private int newButtonPosition = 100;
5
6 public EventDemo()
7 {
8 InitializeComponent();
9 //Anthor按钮单击事件
10 Another.Click += new RoutedEventHandler(Another_Click);
11 }
12
13 //Anthor按钮单击后,执行方法
14 void Another_Click(object sender, RoutedEventArgs e)
15 {
16 //创建一个Button
17 Button b = new Button();
18 //显示内容
19 b.Content = "I live!";
20 //为新创建的控件新建Thickness对象,用来设置Button控件的位置
21 //原文中使用了Canvas.LeftProperty和Canvas.TopProperty
22 Thickness tn = new Thickness(10,this.newButtonPosition,0,0);
23 b.SetValue(Canvas.StyleProperty, tn);
24 //到顶部的距离递增
25 this.newButtonPosition += 30;
26 b.Width = 100;
27 b.Height = 20;
28 //给这个新建的按钮的Click事件添加一个处理方法
29 b.Click += new RoutedEventHandler(b_Click);
30 //添加到父控件,并显示
31 myCanvas.Children.Add(b);
32 }
33
34 //点击添加的控件触发
35 void b_Click(object sender, RoutedEventArgs e)
36 {
37 Button btn = sender as Button;
38 btn.Content = "Don't do that!";
39 btn.IsEnabled = false;
40 }
41 }
42
43