代码式声名silverlight控件

上一个例子是通过vs2008的xaml编辑器来编写silverlight控件的,这里以上一节的demo讲下用代码的方式来添中控件到表现层。


这里是Page.xaml:

  1.    <Grid x:Name="LayoutRoot" Background="White" ShowGridLines="True">
  2.         <Grid.RowDefinitions>
  3.             <RowDefinition />
  4.             <RowDefinition />
  5.             <RowDefinition />
  6.         </Grid.RowDefinitions>
  7.     </Grid>

这里是Page.xaml.cs

  1.    public partial class Page : UserControl
  2.     {
  3.         public Page()
  4.         {
  5.             InitializeComponent();
  6.             this.Loaded += new RoutedEventHandler(Page_Loaded);
  7.         }
  8.         //定义三个控件
  9.         TextBox textinput;
  10.         Button bt;
  11.         TextBlock textoutput;
  12.         void Page_Loaded(object sender, RoutedEventArgs e)
  13.         {
  14.             //实例化textbox
  15.             textinput = new TextBox();
  16.             //设置此控件在所在Grid的第一行的位置
  17.             textinput.SetValue(Grid.RowProperty, 0);
  18.             //设置此控件的四边相对父组件的距离为5个像素
  19.             textinput.Margin = new Thickness(5);
  20.             //把textbox添加到Grid,即实际展示
  21.             this.LayoutRoot.Children.Add(textinput);
  22.             bt = new Button();
  23.             bt.Margin = new Thickness(5);
  24.             bt.SetValue(Grid.RowProperty, 1);
  25.             bt.Content = "click me";
  26.             //注册一个单击事件到此button
  27.             bt.Click += new RoutedEventHandler(bt_Click);
  28.             this.LayoutRoot.Children.Add(bt);
  29.             textoutput = new TextBlock();
  30.             textoutput.TextAlignment = TextAlignment.Center;
  31.             textoutput.Text = "not set";
  32.             textoutput.SetValue(Grid.RowProperty, 2);
  33.             textoutput.Margin = new Thickness(5);
  34.             this.LayoutRoot.Children.Add(textoutput);
  35.         }
  36.         //bt按扭所注册的单击事件
  37.         void bt_Click(object sender, RoutedEventArgs e)
  38.         {
  39.             //让输入的内容显示到输入控件
  40.             textoutput.Text = textinput.Text;
  41.         }
  42.     }

工程文件请到我的资源里下载.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值