微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

代码式声名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.     }

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐