C# 如何使用代码添加控件及控件事件


1.首先简单设计一下界面:
添加了Click事件

<Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <ScrollViewer VerticalScrollBarVisibility="Auto">
        <StackPanel Name="addButtonSp" Margin="5">
            <Button FontSize="20" Foreground="Blue" Click="OnButtonClick">在窗口加入按钮</Button>
        </StackPanel>
    </ScrollViewer>
</Window>

2.在代码部分,简单设计一下控件属性
就是在点击上面Button 按钮时,界面自动添加一个按钮

private void OnButtonClick(object sender, RoutedEventArgs e)
{
    Button btn = new Button();
    btn.Background = Brushes.LightBlue;
    btn.Foreground = Brushes.Yellow;
    btn.Height = 50;
    btn.Content = "按钮";
    btn.Click += new RoutedEventHandler(mes);
    addButtonSp.Children.Add(btn);
}

重点来了,
btn.Click += new RoutedEventHandler(mes);
这行代码,就是用来指定所添加的button控件的点击事件,必须要用RoutedEventHandler(),其次()里面是被调用的事件函数,请往下看:
private void mes(object sender, RoutedEventArgs e),注意参数写法

private void mes(object sender, RoutedEventArgs e)
{
    MessageBoxResult a = MessageBox.Show("你点击了?", "Tip",MessageBoxButton.YesNoCancel,MessageBoxImage.Error);
    if (a == MessageBoxResult.Yes)
    {
        MessageBox.Show("你又点击了?", "haha", MessageBoxButton.OK, MessageBoxImage.Exclamation);
    }
}
这部分的全部代码
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void OnButtonClick(object sender, RoutedEventArgs e)
    {
        Button btn = new Button();
        btn.Background = Brushes.LightBlue;
        btn.Foreground = Brushes.Yellow;
        btn.Height = 50;
        btn.Content = "按钮";
        btn.Click += new RoutedEventHandler(mes);
        addButtonSp.Children.Add(btn);
    }

    private void mes(object sender, RoutedEventArgs e)
    {
        MessageBoxResult a = MessageBox.Show("你点击了?", "Tip",MessageBoxButton.YesNoCancel,MessageBoxImage.Error);
        if (a == MessageBoxResult.Yes)
        {
            MessageBox.Show("你又点击了?", "haha", MessageBoxButton.OK, MessageBoxImage.Exclamation);
        }
        else if(a == MessageBoxResult.No)
        {
            this.Close();
        }
    }

3.结果
a.启动界面

b.疯狂加入按钮

c.随机点击一个按钮

添加button控件,再通过此控件调用其它函数,成功了O(∩_∩)O哈哈~

花絮:
其实,在实验二 图层操作.pdf中,老师给的代码就用了这个代码(>‿◠)✌


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM