上一个例子是通过vs2008的xaml编辑器来编写silverlight控件的,这里以上一节的demo讲下用代码的方式来添中控件到表现层。
这里是Page.xaml:
这里是Page.xaml:
这里是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;
- }
- }
工程文件请到我的资源里下载.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。