上一个例子是通过vs2008的xaml编辑器来编写silverlight控件的,这里以上一节的demo讲下用代码的方式来添中控件到表现层。
这里是Page.xaml:
这里是Page.xaml:
- <Grid x:Name="LayoutRoot" Background="White" ShowGridLines="True">
- <Grid.RowDefinitions>
- <RowDefinition />
- <RowDefinition />
- <RowDefinition />
- </Grid.RowDefinitions>
- </Grid>
这里是Page.xaml.cs
- public partial class Page : UserControl
- {
- public Page()
- {
- InitializeComponent();
- this.Loaded += new RoutedEventHandler(Page_Loaded);
- }
- //定义三个控件
- TextBox textinput;
- Button bt;
- TextBlock textoutput;
- void Page_Loaded(object sender, RoutedEventArgs e)
- {
- //实例化textbox
- textinput = new TextBox();
- //设置此控件在所在Grid的第一行的位置
- textinput.SetValue(Grid.RowProperty, 0);
- //设置此控件的四边相对父组件的距离为5个像素
- textinput.Margin = new Thickness(5);
- //把textbox添加到Grid,即实际展示
- this.LayoutRoot.Children.Add(textinput);
- bt = new Button();
- bt.Margin = new Thickness(5);
- bt.SetValue(Grid.RowProperty, 1);
- bt.Content = "click me";
- //注册一个单击事件到此button
- bt.Click += new RoutedEventHandler(bt_Click);
- this.LayoutRoot.Children.Add(bt);
- textoutput = new TextBlock();
- textoutput.TextAlignment = TextAlignment.Center;
- textoutput.Text = "not set";
- textoutput.SetValue(Grid.RowProperty, 2);
- textoutput.Margin = new Thickness(5);
- this.LayoutRoot.Children.Add(textoutput);
- }
- //bt按扭所注册的单击事件
- void bt_Click(object sender, RoutedEventArgs e)
- {
- //让输入的内容显示到输入控件
- textoutput.Text = textinput.Text;
- }
- }
工程文件请到我的资源里下载.
211

被折叠的 条评论
为什么被折叠?



