一般在创建windows phone应用程序的时候,我们可以直接在UI设计界面设计UI了,只需要从工具箱中托一个想要创建的控件即可。当我们从工具箱中拖一个按钮到MainPage.xaml左侧的设计界面的时候,右侧的silverlight中会自动生成这个Button对应的代码,例如
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <Button Content="Button" Height="82" HorizontalAlignment="Left" Margin="31,37,0,0" Name="button1" VerticalAlignment="Top" Width="181" Click="button1_Click" /> </Grid> </Grid>
我们点击那个按钮,进入的C#代码中为Button添加事件:当点击这个名为“Button”的按钮的时候,会自动给生成一个新的按钮“new Button”
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.Phone.Controls; namespace TestButton { public partial class MainPage : PhoneApplicationPage { // Constructor public MainPage() { InitializeComponent(); } private void button1_Click(object sender, RoutedEventArgs e) { Button myNewButton = new Button(); myNewButton.Name = "button2"; myNewButton.Height = 100; myNewButton.Width = 200; myNewButton.Content = "new Button"; //Thickness中第1、2、3、4个参数分别代表:左、上、右、下 myNewButton.Margin = new Thickness(100.0, 100.0, 100.0, 100.0); // 指示元素应显示相对于父元素的已分配的布局槽的水平轴上的位置 myNewButton.HorizontalAlignment = HorizontalAlignment.Stretch; myNewButton.VerticalAlignment = VerticalAlignment.Stretch; ContentPanel.Children.Add(myNewButton); } } }
运行结果如下:(点击按钮后)