WPF动态添加按钮并相应事件。

来源:互联网 发布:网络通信运营商 编辑:程序博客网 时间:2024/05/16 17:00
上code:

点击(此处)折叠或打开

  1. <Window x:Class="WpfApplication1.MainWindow"
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.         Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
  5.     <Grid>
  6.         <Canvas Name="abc" Margin="0,57,0,0">
  7.             <Button Canvas.Left="400" Canvas.Top="207" Content="Button" Height="30" Name="Button2" Width="85" Click="btn_click"/>
  8.         </Canvas>
  9.     </Grid>
  10. </Window>

上面是布局的时候加了个按钮,下面的代码中会加入个程序中创建的。
 

点击(此处)折叠或打开

  1. namespace WpfApplication1
  2. {
  3.     ///

  4.     /// MainWindow.xaml 的交互逻辑

  5.     ///

  6.     public partial class MainWindow : Window
  7.     {
  8.         public MainWindow()
  9.         {
  10.             InitializeComponent();
  11.             
  12.         }

  13.         private void Window_Loaded(object sender, RoutedEventArgs e)
  14.         {
  15.             Button btn = new Button
  16.                 {
  17.                     Name = "Button1",
  18.                     Content = "OK",
  19.                     Height = 23,
  20.                     Width = 64,
  21.                     HorizontalAlignment = HorizontalAlignment.Left,
  22.                     Margin = new Thickness(10, 10, 0, 0),
  23.                     VerticalAlignment = VerticalAlignment.Top,
  24.                     Visibility = Visibility.Visible
  25.                 };
  26.             btn.Click += new RoutedEventHandler(btn_click);
  27.             abc.Children.Add(btn);

  28.         }
  29.         private void btn_click(object sender, RoutedEventArgs e)
  30.         {
  31.             Button btn = sender as Button;
  32.             if ("Button1" == btn.Name)
  33.             {
  34.                 System.Windows.MessageBox.Show("hello");
  35.             }
  36.             else if ("Button2"== btn.Name)
  37.             {
  38.                 System.Windows.MessageBox.Show("World.");
  39.             }

  40.         }
  41.     }
  42. }

1 0
原创粉丝点击